#!/usr/bin/env bash
#
# install.sh - co.nr CLI installer
# Version  : 0.4.1
# Released : 2026-07-13
# Checksum : sha256:bc14c7123008b79ce5113383add087406eec8803f20b6a0d20cd692e453cb089
#
# What this script does:
#  1. Detects OS, architecture, KVM availability, and Docker status
#  2. Downloads the appropriate conr-cli binary from install.co.nr
#  3. Verifies the binary checksum
#  4. Installs to ~/.local/bin (user) or /usr/local/bin (system)
#
# Configuration paths after install:
#  > User install   binary : ~/.local/bin/conr
#                   config : ~/.config/conr/conr.{yaml,jsonc}
#                   data   : ~/.local/share/conr
#
#  > System install binary : /usr/local/bin/conr
#                   config : /etc/conr/conr.{yaml,jsonc}
#                   data   : /var/lib/conr
#
#   Auth credentials are always stored in the user's home directory,
#   regardless of install scope. Config accepts either conr.yaml or
#   conr.jsonc; conr-cli checks both, preferring .yaml when both exist.
#   Config can be stored in /etc/conr/conr.yaml or ~/.config/conr/conr.yaml
#   or both, where user config is overlayed on system config.
#
# Quick install:
#   curl -fsSL https://install.co.nr | bash
#
# Options (append after --):
#   curl -fsSL https://install.co.nr | bash -s -- [OPTIONS]
#
#   --system          Install system-wide to /usr/local/bin (requires sudo)
#   --user            Install to ~/.local/bin (default)
#   --prefix <path>   Install to a custom directory
#   --version <ver>   Install a specific version instead of latest
#   --token <tok>     Bearer auth token for authenticated downloads
#   --no-verify       Skip binary checksum verification
#   --interactive     Prompt for all options interactively
#   -y, --yes         Non-interactive; accept all defaults
#
# Examples:
#   curl -fsSL https://install.co.nr | bash -s -- --system
#   curl -fsSL https://install.co.nr | bash -s -- --version 1.2.3 --user
#   curl -fsSL https://install.co.nr | bash -s -- --interactive
#
# To verify this script's integrity after downloading:
#   sed '1,/^[^#]/d' install.sh | sha256sum
#
# Note: This deletes lines 1-N until the first non-comment line, leaving all
# executable code and inline comments for hashing. This allows the checksum in
# file header without invalidating the checksum.
#
set -euo pipefail

readonly BASE_URL="https://install.co.nr"
readonly ASSET_NAME="conr-cli"
readonly BINARY_NAME="conr"
readonly INSTALLER_VERSION="0.4.1"

if [[ -t 1 ]] && [[ "${NO_COLOR:-}" == "" ]]; then
  BOLD='\033[1m'
  DIM='\033[2m'
  RED='\033[0;31m'
  GREEN='\033[0;32m'
  YELLOW='\033[0;33m'
  BLUE='\033[0;34m'
  PURPLE='\033[0;35m'
  CYAN='\033[0;36m'
  WHITE='\033[0;37m'
  RESET='\033[0m'
else
  BOLD='' DIM='' RED='' GREEN='' YELLOW='' BLUE='' PURPLE='' CYAN='' WHITE='' RESET=''
fi

log_step()    { echo -e "${BOLD}${CYAN}▸${RESET} $*${RESET}"; }
log_info()    { echo -e "${WHITE}   $*${RESET}"; }
log_ok()      { echo -e "${GREEN} ✓ $*${RESET}"; }
log_warn()    { echo -e "${YELLOW} ⚠ $*${RESET}"; }
log_error()   { local _line="${RED} ✗ $*${RESET}"; echo -e "$_line" >&2; [[ -n "${LOG_FILE:-}" ]] && echo -e "$_line" >> "${LOG_FILE}"; }
log_detail()  { echo -e "${DIM}   $*${RESET}"; }
log_kv()      { echo -e "   ${BOLD}${CYAN}${1}${RESET} ${2}"; }
log_ok_kv()   { echo -e "${GREEN} ✓${RESET} ${BOLD}${CYAN}${1}${RESET} ${2}"; }
log_warn_kv() { echo -e "${YELLOW} ⚠${RESET} ${BOLD}${CYAN}${1}${RESET} ${2}"; }

die() {
  log_error "$*"
  exit 1
}

maybe_sudo() {
  if [[ "$EUID" -eq 0 ]]; then
    "$@"
  elif command -v sudo &>/dev/null; then
    sudo "$@"
  else
    die "This operation requires root privileges but sudo is not available; re-run as root or use --user"
  fi
}

run_scoped() {
  local scope="$1"
  shift
  if [[ "$scope" == "system" ]]; then
    maybe_sudo "$@"
  else
    "$@"
  fi
}

has_tty() {
  [[ -e /dev/tty ]] && { : </dev/tty; } 2>/dev/null
}

banner() {
  echo
  echo -e "${BOLD}${CYAN}  ╭───────────────────────────────╮${RESET}"
  echo -e "${BOLD}${CYAN}  │  🚀 co.nr CLI installer       │${RESET}"
  echo -e "${BOLD}${CYAN}  │     v0.4.1                    │${RESET}"
  echo -e "${BOLD}${CYAN}  ╰───────────────────────────────╯${RESET}"
  echo
}

OPT_SCOPE=""   # "user" | "system" | ""
OPT_PREFIX=""  # custom install prefix
OPT_VERSION="latest"
OPT_TOKEN=""
OPT_NO_VERIFY=false
OPT_INTERACTIVE=false
OPT_YES=false

parse_args() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      --system)       OPT_SCOPE="system" ;;
      --user)         OPT_SCOPE="user" ;;
      --prefix)       OPT_PREFIX="${2:?--prefix requires a path}"; shift ;;
      --prefix=*)     OPT_PREFIX="${1#*=}" ;;
      --version)      OPT_VERSION="${2:?--version requires a value}"; shift ;;
      --version=*)    OPT_VERSION="${1#*=}" ;;
      --token)        OPT_TOKEN="${2:?--token requires a value}"; shift ;;
      --token=*)      OPT_TOKEN="${1#*=}" ;;
      --no-verify)    OPT_NO_VERIFY=true ;;
      --interactive)  OPT_INTERACTIVE=true ;;
      -y|--yes)       OPT_YES=true ;;
      -h|--help)      usage; exit 0 ;;
      *)              die "Unknown option: $1 (try --help)" ;;
    esac
    shift
  done

  if [[ "$OPT_INTERACTIVE" == true && "$OPT_YES" == true ]]; then
    log_warn "--interactive and --yes are both set; prompts will appear but confirmations will be auto-accepted"
  fi
}

usage() {
  cat << 'EOF'
Quick install:
  curl -fsSL https://install.co.nr | bash

Options (append after --):
  curl -fsSL https://install.co.nr | bash -s -- [OPTIONS]
  --system          Install system-wide to /usr/local/bin (requires sudo)
  --user            Install to ~/.local/bin (default)
  --prefix <path>   Install to a custom directory
  --version <ver>   Install a specific version instead of latest
  --token <tok>     Bearer auth token for authenticated downloads
  --no-verify       Skip binary checksum verification
  --interactive     Prompt for all options interactively
  -y, --yes         Non-interactive; accept all defaults

Configuration paths after install:
  > User install   binary : ~/.local/bin/conr
                   config : ~/.config/conr/conr.{yaml,jsonc}
                   data   : ~/.local/share/conr

  > System install binary : /usr/local/bin/conr
                   config : /etc/conr/conr.{yaml,jsonc}
                   data   : /var/lib/conr

  Auth credentials are always stored in the user's home directory,
  regardless of install scope. Config accepts either conr.yaml or
  conr.jsonc; conr-cli checks both, preferring .yaml when both exist.
  Config can be stored in /etc/conr/conr.yaml or ~/.config/conr/conr.yaml
  or both, where user config is overlayed on system config.

Examples:
  curl -fsSL https://install.co.nr | bash -s -- --system
  curl -fsSL https://install.co.nr | bash -s -- --version 1.2.3 --user
  curl -fsSL https://install.co.nr | bash -s -- --interactive
EOF
}

detect_os() {
  local os
  os="$(uname -s)"
  case "$os" in
    Linux)   echo "linux" ;;
    Darwin)  echo "apple" ;;
    *)       die "Unsupported operating system: $os" ;;
  esac
}

detect_arch() {
  local arch
  arch="$(uname -m)"
  case "$arch" in
    x86_64)          echo "x86_64" ;;
    aarch64|arm64)   echo "aarch64" ;;
    *)               die "Unsupported architecture: $arch" ;;
  esac
}

detect_kvm() {
  if [[ -c /dev/kvm ]]; then
    if [[ -r /dev/kvm && -w /dev/kvm ]]; then
      echo "available"
    else
      echo "present_no_access"
    fi
  elif grep -qE '^flags.*(vmx|svm)' /proc/cpuinfo 2>/dev/null; then
    echo "cpu_supported"
  else
    echo "unavailable"
  fi
}

detect_docker() {
  if command -v docker &>/dev/null; then
    if docker info &>/dev/null; then
      echo "running"
    else
      echo "installed_not_running"
    fi
  elif [[ -S /var/run/docker.sock ]]; then
    echo "socket_present"
  else
    echo "unavailable"
  fi
}

detect_existing_install() {
  command -v "${BINARY_NAME}" 2>/dev/null || true
}

first_in_path() {
  # Prints whichever of the two dirs appears first in $PATH
  local a="$1" b="$2" d
  local IFS=':'
  for d in $PATH; do
    if [[ "$d" == "$a" ]]; then echo "$a"; return; fi
    if [[ "$d" == "$b" ]]; then echo "$b"; return; fi
  done
}

require_cmd() {
  command -v "$1" &>/dev/null || die "Required tool not found: $1"
}

download_file() {
  local url="$1"
  local dest="$2"
  local label="${3:-Downloading}"
  local token="${4:-}"

  log_step "${label}"
  log_detail "${url}"

  local http_code
  if command -v curl &>/dev/null; then
    local -a curl_args=(-L --progress-bar -w "%{http_code}" -o "$dest")
    [[ -n "$token" ]] && curl_args+=(-H "Authorization: Bearer $token")
    http_code=$(curl "${curl_args[@]}" "$url") || true
  elif command -v wget &>/dev/null; then
    local -a wget_args=(--show-progress --server-response -O "$dest")
    [[ -n "$token" ]] && wget_args+=(--header="Authorization: Bearer $token")
    local tmp_stderr
    tmp_stderr=$(mktemp)
    wget "${wget_args[@]}" "$url" 2> >(tee "$tmp_stderr" >&2) || true
    http_code=$(awk '/HTTP\//{code=$2} END{print code+0}' "$tmp_stderr")
    rm -f "$tmp_stderr"
  else
    die "Neither curl nor wget found; cannot download files :("
  fi

  case "${http_code:-0}" in
    2??)  return 0 ;;
    401)  log_error "Download failed: ${url}  (authentication required)"; return 2 ;;
    *)    log_error "Download failed: ${url}"; return 1 ;;
  esac
}

verify_checksum() {
  local file="$1"
  local expected="$2"

  log_step "${CYAN}${BOLD}Verifying checksum${RESET}"

  local actual
  if command -v sha256sum &>/dev/null; then
    actual="$(sha256sum "$file" | awk '{print $1}')"
  elif command -v shasum &>/dev/null; then
    actual="$(shasum -a 256 "$file" | awk '{print $1}')"
  else
    log_warn "No sha256 tool found; skipping checksum verification :s"
    return 0
  fi

  if [[ "$actual" != "$expected" ]]; then
    die "\nChecksum mismatch!\n    expected: $expected\n    got:      $actual\n\n"
  fi

  log_ok "Checksum verified    ${DIM}sha256:${actual}"
}

resolve_install_dir() {
  local scope="$1"

  if [[ -n "$OPT_PREFIX" ]]; then
    echo "$OPT_PREFIX"
    return
  fi

  case "$scope" in
    system)  echo "/usr/local/bin" ;;
    user)    echo "${HOME}/.local/bin" ;;
    *)       echo "${HOME}/.local/bin" ;;
  esac
}

resolve_config_dir() {
  local scope="$1"
  case "$scope" in
    system) echo "/etc/conr" ;;
    *)      echo "${HOME}/.config/conr" ;;
  esac
}

ensure_dir() {
  local dir="$1"
  local scope="$2"

  if [[ ! -d "$dir" ]]; then
    log_step "${CYAN}${BOLD}Creating directory ${GREEN}${dir}${RESET}"
    run_scoped "$scope" mkdir -p "$dir"
  fi
}

install_binary() {
  local src="$1"
  local dest="$2"
  local scope="$3"

  chmod +x "$src"

  if [[ "$scope" == "system" ]]; then
    log_step "${CYAN}${BOLD}Installing to ${GREEN}${dest} ${DIM}(elevated)${RESET}"
    run_scoped system mv "$src" "$dest"
    run_scoped system chown root:root "$dest"
  else
    log_step "${CYAN}${BOLD}Installing to ${dest}${RESET}"
    mv "$src" "$dest"
  fi
  run_scoped "$scope" chmod 755 "$dest"
}

create_default_file() {
  local scope="$1"
  local file="$2"
  local mode="$3"
  local label="$4"
  local content="$5"

  if [[ -f "$file" ]]; then
    return 0
  fi

  if [[ "$scope" == "system" ]]; then
    log_step "${CYAN}${BOLD}Creating ${label} ${DIM}${file} (elevated)${RESET}"
  else
    log_step "${CYAN}${BOLD}Creating ${label} ${DIM}${file}${RESET}"
  fi
  printf '%s\n' "$content" | run_scoped "$scope" tee "$file" > /dev/null
  run_scoped "$scope" chmod "$mode" "$file"
}

ensure_config_files() {
  local scope="$1"
  local conf_dir cred_dir
  conf_dir="$(resolve_config_dir "$scope")"
  # Credentials are always per-user, regardless of install scope
  cred_dir="${HOME}/.config/conr"

  ensure_dir "$conf_dir" "$scope"
  create_default_file "$scope" "${conf_dir}/conr.yaml" 644 "config file" "# co.nr configuration file"

  ensure_dir "$cred_dir" user
  create_default_file user "${cred_dir}/credentials.yaml" 600 "credentials file" "# co.nr credentials file
#
# Holds this device's x509 certificates (PEM), issued and pinned by the
# conr CA and bound to the device's TPM/SE hardware keypair. All profiles
# share this file for authentication.
#
# Provisioned by \`conr complete-install\`; do not copy between devices."
}

update_shell_rc_files() {
  local install_dir="$1"
  local path_export="export PATH=\"${install_dir}:\$PATH\""

  local shells=("$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.config/fish/config.fish")
  local updated=false

  log_step "${CYAN}${BOLD}Updating shell configuration files${RESET}"

  for rc_file in "${shells[@]}"; do
    if [[ ! -f "$rc_file" ]]; then
      continue
    fi

    if grep -qF "$install_dir" "$rc_file" 2>/dev/null; then
      log_detail "✓ ${rc_file}  (already configured)"
      continue
    fi

    if [[ "$rc_file" == *"fish"* ]]; then
      echo "" >> "$rc_file"
      echo "# Added by conr-cli installer" >> "$rc_file"
      echo "set -gx PATH $install_dir $PATH" >> "$rc_file"
      log_ok_kv "Updated" "${rc_file}"
    else
      echo "" >> "$rc_file"
      echo "# Added by conr-cli installer" >> "$rc_file"
      echo "$path_export" >> "$rc_file"
      log_ok_kv "Updated" "${rc_file}"
    fi
    updated=true
  done

  if [[ "$updated" == true ]]; then
    echo
    log_info "Shell configuration updated. ${DIM}${install_dir} is added to PATH.${RESET}"
  fi

  if ! echo "$PATH" | tr ':' '\n' | grep -qxF "$install_dir"; then
    export PATH="${install_dir}:$PATH"
    echo
    log_info "${DIM}conr-cli not found on PATH. Added to PATH for this session${RESET}"
    log_info "  export PATH=\"${install_dir}:\$PATH\""
  fi
}

prompt_scope() {
  echo -e "  ${BOLD}Install location:${RESET}"
  echo -e "    ${CYAN}[1]${RESET} User only    ~/.local/bin  ${DIM}(default)${RESET}"
  echo -e "    ${CYAN}[2]${RESET} System-wide  /usr/local/bin  ${DIM}(requires sudo)${RESET}"
  echo -e "    ${CYAN}[3]${RESET} Custom path"
  echo
  read -rp "  Choice [1]: " choice </dev/tty
  case "${choice:-1}" in
    1) OPT_SCOPE="user" ;;
    2) OPT_SCOPE="system" ;;
    3)
      read -rp "  Install path: " OPT_PREFIX </dev/tty
      OPT_SCOPE="user"
      ;;
    *) log_warn "Invalid choice - defaulting to user install"; OPT_SCOPE="user" ;;
  esac
}

prompt_version() {
  read -rp "  Version to install [latest]: " ver </dev/tty
  OPT_VERSION="${ver:-latest}"
}

confirm() {
  local prompt="$1"
  if [[ "$OPT_YES" == true ]]; then
    return 0
  fi
  if ! has_tty; then
    die "No interactive terminal available; re-run with --yes to accept defaults"
  fi
  read -rp "${prompt} [Y/n]: " answer </dev/tty
  [[ "${answer:-Y}" =~ ^[Yy]$ ]]
}

prompt_token() {
  local prompt_msg="${1:-Auth token (leave empty to skip)}"
  read -rsp "  ${prompt_msg}: " OPT_TOKEN </dev/tty
  echo
}

# Main

LOG_FILE=""
_LOG_PID=""
_ALT_SCREEN=false
tmp_dir=""

_cleanup_exit() {
  # Restore stdout and wait for tee to drain
  if [[ -n "${_LOG_PID:-}" ]]; then
    exec 1>&9 9>&-
    wait "$_LOG_PID" 2>/dev/null || true
  fi
  # Leave alt screen and replay log
  if [[ "$_ALT_SCREEN" == true ]]; then
    printf '\033[?1049l'
    if [[ -s "${LOG_FILE:-}" ]]; then
      cat "${LOG_FILE}"
    fi
  fi
  if [[ -s "${LOG_FILE:-}" ]]; then
    printf '\n'
    echo -e "${DIM}  Install log: ${CYAN}${LOG_FILE}${RESET}"
  fi
  rm -rf "${tmp_dir:-}"
}

check_dependencies() {
  require_cmd mktemp
  require_cmd awk
  if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then
    die "Neither curl nor wget found; cannot download files :("
  fi
}

verify_self_integrity() {
  local self="${BASH_SOURCE[0]:-}"

  # When piped straight into bash (the "curl | bash" quick install), there is
  # no script file on disk to hash - only stdin, which bash has already
  # consumed. Self-verification only applies when running from a real file.
  if [[ -z "$self" || ! -f "$self" ]]; then
    return 0
  fi

  local expected
  expected="$(sed -n 's/^# Checksum : sha256:\(.*\)/\1/p' "$self" | head -n1)"

  local actual
  if command -v sha256sum &>/dev/null; then
    actual="$(sed '1,/^[^#]/d' "$self" | sha256sum)"
  elif command -v shasum &>/dev/null; then
    actual="$(sed '1,/^[^#]/d' "$self" | shasum -a 256)"
  else
    log_warn "No sha256 tool found; skipping script integrity check :s"
    return 0
  fi

  if [[ "$actual" != "$expected" ]]; then
    die "Script integrity check failed!\n\n    expected: $expected\n    got:      $actual\n\nThis script was modified and should not be trusted; download a fresh copy from ${BASE_URL}\n"
  fi
}

setup_logging() {
  if [[ -t 1 ]]; then
    printf '\033[?1049h\033[H'
    _ALT_SCREEN=true
  fi
  LOG_FILE="$(mktemp "${TMPDIR:-/tmp}/conr-install_$(date +%Y%m%d_%H%M%S)_XXXXXX.log")"
  exec 9>&1
  exec > >(tee "${LOG_FILE}")
  _LOG_PID=$!
  trap '_cleanup_exit' EXIT
  trap 'exit 130' INT
  trap 'exit 143' TERM
}

main() {
  verify_self_integrity
  parse_args "$@"
  check_dependencies

  if [[ "$OPT_INTERACTIVE" == true ]] && ! has_tty; then
    die "--interactive requires a terminal but /dev/tty is not available"
  fi

  setup_logging

  banner

  log_step "${CYAN}${BOLD}Detecting environment${RESET}"

  local os arch kvm_status docker_status existing_bin
  os="$(detect_os)"
  arch="$(detect_arch)"
  kvm_status="$(detect_kvm)"
  docker_status="$(detect_docker)"
  existing_bin="$(detect_existing_install)"

  log_ok_kv "    OS" "${PURPLE}${os}${RESET} / ${BLUE}${arch}"

  case "$kvm_status" in
    available)         log_ok_kv   "   KVM" "${GREEN}available" ;;
    present_no_access) log_warn_kv "   KVM" "${YELLOW}present but not accessible (user needs to be in the kvm group)" ;;
    cpu_supported)     log_warn_kv "   KVM" "${YELLOW}CPU supports virtualisation but /dev/kvm not present" ;;
    unavailable)       log_kv      "   KVM" "${RED}unavailable${RESET}  ${DIM}vmm will be disabled" ;;
  esac

  case "$docker_status" in
    running)               log_ok_kv   "Docker" "${GREEN}running" ;;
    installed_not_running) log_warn_kv "Docker" "${YELLOW}installed but daemon is not running" ;;
    socket_present)        log_kv      "Docker" "${YELLOW}socket found" ;;
    unavailable)           log_kv      "Docker" "${RED}not found${RESET}    ${DIM}docker support will be disabled" ;;
  esac

  if [[ -n "$existing_bin" ]]; then
    local existing_ver
    existing_ver="$("$existing_bin" --version 2>/dev/null | head -n 1 || true)"
    log_warn_kv "  conr" "${YELLOW}already installed at ${existing_bin}${existing_ver:+ ${DIM}(${existing_ver})}"
  fi

  if [[ "$OPT_INTERACTIVE" == true ]]; then
    echo
    prompt_scope
    prompt_version
    if [[ -z "$OPT_TOKEN" ]]; then
      prompt_token
    fi
  fi

  if [[ -z "$OPT_SCOPE" ]]; then
    if [[ "$EUID" -eq 0 ]]; then
      OPT_SCOPE="system"
    else
      OPT_SCOPE="user"
    fi
  fi

  local install_dir
  install_dir="$(resolve_install_dir "$OPT_SCOPE")"
  local install_dest="${install_dir}/${BINARY_NAME}"

  local config_dir
  config_dir="$(resolve_config_dir "$OPT_SCOPE")"
  local credentials_file="${HOME}/.config/conr/credentials.yaml"

  local asset_name="${ASSET_NAME}_${os}_${arch}"
  local version_path
  if [[ "$OPT_VERSION" == "latest" ]]; then
    version_path=""
  else
    version_path="/v${OPT_VERSION}"
  fi
  local download_url="${BASE_URL}/${asset_name}${version_path}"
  local checksum_url="${download_url}.sha256"

  echo
  log_step "${CYAN}${BOLD}Install plan${RESET}"
  log_kv " Binary" "${PURPLE}${asset_name}"
  log_kv "Version" "${PURPLE}${OPT_VERSION}"
  log_kv "Install" "${GREEN}${install_dest}"
  log_kv "  Scope" "${YELLOW}${OPT_SCOPE}"
  echo
  log_step "${CYAN}${BOLD}Configuration paths${RESET}"
  log_kv "Config file" "${YELLOW}${DIM}${config_dir}/conr.yaml"
  log_kv "Credentials" "${YELLOW}${DIM}${credentials_file}${RESET}"
  echo

  if [[ -n "$existing_bin" && "$existing_bin" != "$install_dest" ]]; then
    local existing_dir
    existing_dir="$(dirname "$existing_bin")"
    log_warn "Existing conr binary at ${existing_bin} is not the install target"
    if [[ "$(first_in_path "$existing_dir" "$install_dir")" == "$existing_dir" ]]; then
      log_info "${YELLOW}${existing_dir} precedes ${install_dir} in PATH, so the existing binary will shadow the new one.${RESET}"
    fi
    if [[ "$EUID" -ne 0 && ! -w "$existing_bin" ]]; then
      log_info "${YELLOW}It cannot be replaced without root (current UID: ${EUID}); re-run with --system, or remove it manually.${RESET}"
    fi
    echo
  fi

  if [[ "$OPT_YES" == false && "$OPT_INTERACTIVE" == false ]]; then
    confirm "Proceed with installation?" || { echo; log_info "Aborted."; exit 0; }
    echo
  fi

  if [[ "$OPT_SCOPE" == "system" ]]; then
    if [[ "$EUID" -ne 0 ]]; then
      log_step "System install requires elevated privileges"
      if ! command -v sudo &>/dev/null; then
        die "sudo is not available; re-run as root or use --user"
      fi
      sudo -v || die "sudo authorisation failed"
    fi
  fi

  tmp_dir="$(mktemp -d)"

  local tmp_bin="${tmp_dir}/${BINARY_NAME}"
  local tmp_sum="${tmp_dir}/${BINARY_NAME}.sha256"

  local dl_exit=0
  download_file "$download_url" "$tmp_bin" "${CYAN}${BOLD}Downloading ${asset_name}${RESET}" "$OPT_TOKEN" || dl_exit=$?
  if [[ $dl_exit -ne 0 ]]; then
    if [[ $dl_exit -eq 2 ]] && has_tty; then
      prompt_token "Enter auth token to retry"
      [[ -n "$OPT_TOKEN" ]] || die "No auth token provided"
      download_file "$download_url" "$tmp_bin" "${CYAN}${BOLD}Retrying download with auth token${RESET}" "$OPT_TOKEN" \
        || die "Download failed: ${download_url}"
    else
      die "Download failed: ${download_url}"
    fi
  fi
  echo

  if [[ "$OPT_NO_VERIFY" == false ]]; then
    download_file "$checksum_url" "$tmp_sum" "${CYAN}${BOLD}Fetching checksum${RESET}" "$OPT_TOKEN" \
      || die "Download failed: ${checksum_url}"
    echo
    local expected_sum
    expected_sum="$(awk '{print $1}' "$tmp_sum")"
    verify_checksum "$tmp_bin" "$expected_sum"
  else
    log_warn "Checksum verification skipped (--no-verify)"
  fi

  echo
  ensure_dir "$install_dir" "$OPT_SCOPE"
  install_binary "$tmp_bin" "$install_dest" "$OPT_SCOPE"

  echo
  ensure_config_files "$OPT_SCOPE"

  log_ok "${BOLD}conr-cli installed successfully${RESET}"
  echo
  log_kv "Main binary" "${YELLOW}${install_dir}${BOLD}/conr${RESET}"
  log_kv "Config file" "${YELLOW}${DIM}${config_dir}${BOLD}/conr.yaml${RESET}"
  log_kv "Credentials" "${YELLOW}${DIM}${config_dir}${BOLD}/credentials.yaml${RESET}"
  echo

  if [[ "$OPT_SCOPE" == "system" ]]; then
    log_info  "System config in ${config_dir}/ applies to all users; each user's"
    log_info  "auth credentials are stored privately in their own ~/.config/conr/"
  fi
  if ! echo "$PATH" | tr ':' '\n' | grep -qxF "$install_dir"; then
    update_shell_rc_files "$install_dir"
  else
    log_ok "${BOLD}${install_dir}${RESET} ${GREEN}is already on PATH${RESET}"
  fi
  echo

  log_step "${CYAN}${BOLD}Running \`conr complete-install\` to provision device keys...${RESET}"
  local ci_status=0
  "$install_dest" complete-install 2>&1 || ci_status=$?
  if [[ $ci_status -ne 0 ]]; then
    echo
    log_warn "conr complete-install failed (exit ${ci_status}); the binary itself installed successfully."
    log_info "Complete the setup later by running: ${CYAN}${install_dest} complete-install${RESET}"
  fi

  exit 0
}

main "$@"
