#!/usr/bin/env bash
# Riptides daemon installer for Linux
#
# Usage:
#   # Join token (generate one in the Riptides UI):
#   curl -fsSL https://docs.riptides.io/install.sh | sudo bash -s -- \
#     --controlplane-url https://<env-id>.console.riptides.io \
#     --join-token <token>
#
#   # EC2 — auto-detected, no token required:
#   curl -fsSL https://docs.riptides.io/install.sh | sudo bash -s -- \
#     --controlplane-url https://<env-id>.console.riptides.io
#
#   # Azure VM — auto-detected, no token required:
#   curl -fsSL https://docs.riptides.io/install.sh | sudo bash -s -- \
#     --controlplane-url https://<env-id>.console.riptides.io
#
#   # GCP VM — auto-detected, no token required:
#   curl -fsSL https://docs.riptides.io/install.sh | sudo bash -s -- \
#     --controlplane-url https://<env-id>.console.riptides.io

set -euo pipefail

# ── Defaults ──────────────────────────────────────────────────────────────────
DAEMON_VERSION="${DAEMON_VERSION:-latest}"
DRIVER_VERSION="${DRIVER_VERSION:-}"
CONTROL_PLANE=""
JOIN_TOKEN=""
GITHUB_TOKEN="${GITHUB_TOKEN:-}"
DATA_DIR="/var/lib/riptides"
VERBOSE=false
USE_AWSIID=""                 # set to 1 to use EC2 Instance Identity Document auth
USE_AZUREIMDS=""              # set to 1 to use Azure Instance Metadata Service auth
AZUREIMDS_RESOURCE=""         # --azureimds-resource
USE_GCPIIT=""                 # set to 1 to use GCP Instance Identity Token auth
GCPIIT_AUDIENCE=""            # --gcpiit-audience
USE_GITHUB_ACTIONS=""         # set to 1 to use GitHub Actions OIDC auth (auto-detected)
PLUGIN=""                     # --plugin (explicit auth plugin type)
GITHUB_ACTIONS_AUDIENCE="riptides"  # --github-actions-audience
K8SSAT_CLUSTER_ID=""          # --k8ssat-cluster-id
K8SSAT_TOKEN_PATH=""          # --k8ssat-token-path
JWT_ISSUER=""                 # --jwt-issuer
JWT_TOKEN_PATH=""             # --jwt-token-path
SSHCERTPOP_KEY_PATH=""        # --sshcertpop-key-path
SSHCERTPOP_CERT_PATH=""       # --sshcertpop-cert-path
X509CERTPOP_KEY_PATH=""       # --x509certpop-key-path
X509CERTPOP_CERT_PATH=""      # --x509certpop-cert-path

# ── Colours ───────────────────────────────────────────────────────────────────
if [[ -t 1 ]]; then
  GREEN='\033[0;32m'; YELLOW='\033[1;33m'; RED='\033[0;31m'; BOLD='\033[1m'; NC='\033[0m'
else
  GREEN=''; YELLOW=''; RED=''; BOLD=''; NC=''
fi

info()  { printf "${GREEN}  ✓${NC}  %s\n" "$*"; }
step()  { printf "\n${BOLD}▶ %s${NC}\n"   "$*"; }
warn()  { printf "${YELLOW}  ⚠${NC}  %s\n" "$*"; }

spin() {
  local msg="$1" i=0 frames=('⠋' '⠙' '⠹' '⠸' '⠼' '⠴' '⠦' '⠧' '⠇' '⠏')
  while true; do
    printf "\r  ${BOLD}%s${NC}  %s " "${frames[$(( i % ${#frames[@]} ))]}" "$msg"
    (( i++ )) || true
    sleep 0.1
  done
}

# Usage: with_spinner "message" cmd [args...]
# Runs cmd in background, shows spinner until it exits.
with_spinner() {
  local msg="$1"; shift
  spin "$msg" &
  local spin_pid=$!
  "$@"
  local rc=$?
  kill "$spin_pid" 2>/dev/null || true; wait "$spin_pid" 2>/dev/null || true
  printf "\r\033[K"  # clear the spinner line
  return $rc
}
fatal() { printf "${RED}  ✗  ${NC}" >&2; printf "%b\n" "$*" >&2; exit 1; }

# ── Usage ─────────────────────────────────────────────────────────────────────
usage() {
  cat <<EOF
Riptides daemon installer

Usage:
  # EC2 node — join via AWS Instance Identity Document (no token needed):
  install.sh --controlplane-url URL --awsiid [OPTIONS]

  # Azure VM — join via Azure Instance Metadata Service (no token needed):
  install.sh --controlplane-url URL --azureimds [OPTIONS]

  # GCP VM — join via GCP Instance Identity Token (no token needed):
  install.sh --controlplane-url URL --gcpiit [OPTIONS]

  # GitHub Actions runner — join via OIDC (auto-detected inside Actions, no token needed):
  install.sh --controlplane-url URL --github-actions-audience AUDIENCE [OPTIONS]

  # Join with an existing token:
  install.sh --controlplane-url URL --join-token TOKEN [OPTIONS]

Required:
  --controlplane-url URL     Control plane URL (e.g. https://abc123.console.riptides.io)

Options:
  --join-token              TOKEN   Join token value
  --plugin                  TYPE    Explicit auth plugin (AWSIID, AzureIMDS, GCPIIT, GitHubActions, K8sSAT, JWT, SSHCertPOP, X509CertPOP)
  --awsiid                          Use AWS Instance Identity Document auth (auto-detected on EC2)
  --azureimds                       Use Azure Instance Metadata Service auth (auto-detected on Azure)
  --azureimds-resource      URI     Azure resource/audience override (default: https://management.azure.com/)
  --gcpiit                          Use GCP Instance Identity Token auth (auto-detected on GCP)
  --gcpiit-audience         STRING  GCP identity token audience override
  --github-actions-audience STRING  GitHub Actions OIDC audience (default: riptides)
  --k8ssat-cluster-id       ID      Kubernetes SAT cluster ID
  --k8ssat-token-path       PATH    Kubernetes SAT token file path
  --jwt-issuer              URL     JWT issuer (required for JWT auth)
  --jwt-token-path          PATH    JWT token file path
  --sshcertpop-key-path     PATH    SSH private key path (SSHCertPOP auth)
  --sshcertpop-cert-path    PATH    SSH certificate path (SSHCertPOP auth)
  --x509certpop-key-path    PATH    X.509 private key path (X509CertPOP auth)
  --x509certpop-cert-path   PATH    X.509 certificate path (X509CertPOP auth)
  --daemon-version          VERSION Daemon version        (default: latest; also \$DAEMON_VERSION)
  --driver-version          VERSION Driver version        (default: latest, resolved by driver-loader)
  --data-dir                DIR     Daemon data directory  (default: /var/lib/riptides)
  --github-token            TOKEN   GitHub token for package download (or \$GITHUB_TOKEN)
  --verbose, -v                     Show full output from package manager and systemctl
  --help                            Show this help

Environment variables:
  DAEMON_VERSION     Same as --daemon-version
  GITHUB_TOKEN       Same as --github-token
  AUDIENCE           Same as --audience
EOF
}

# ── Argument parsing ──────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
  case "$1" in
    --controlplane-url)          CONTROL_PLANE="$2";            shift 2 ;;
    --join-token)                JOIN_TOKEN="$2";               shift 2 ;;
    --plugin)                    PLUGIN="$2";                   shift 2 ;;
    --awsiid)                    USE_AWSIID=1;                  shift   ;;
    --azureimds)                 USE_AZUREIMDS=1;               shift   ;;
    --azureimds-resource)        AZUREIMDS_RESOURCE="$2";       shift 2 ;;
    --gcpiit)                    USE_GCPIIT=1;                  shift   ;;
    --gcpiit-audience)           GCPIIT_AUDIENCE="$2";          shift 2 ;;
    --github-actions-audience)   GITHUB_ACTIONS_AUDIENCE="$2";  shift 2 ;;
    --k8ssat-cluster-id)         K8SSAT_CLUSTER_ID="$2";        shift 2 ;;
    --k8ssat-token-path)         K8SSAT_TOKEN_PATH="$2";        shift 2 ;;
    --jwt-issuer)                JWT_ISSUER="$2";               shift 2 ;;
    --jwt-token-path)            JWT_TOKEN_PATH="$2";           shift 2 ;;
    --sshcertpop-key-path)       SSHCERTPOP_KEY_PATH="$2";      shift 2 ;;
    --sshcertpop-cert-path)      SSHCERTPOP_CERT_PATH="$2";     shift 2 ;;
    --x509certpop-key-path)      X509CERTPOP_KEY_PATH="$2";     shift 2 ;;
    --x509certpop-cert-path)     X509CERTPOP_CERT_PATH="$2";    shift 2 ;;
    --daemon-version)            DAEMON_VERSION="$2";           shift 2 ;;
    --driver-version)            DRIVER_VERSION="$2";           shift 2 ;;
    --data-dir)                  DATA_DIR="$2";                 shift 2 ;;
    --github-token)              GITHUB_TOKEN="$2";             shift 2 ;;
    --verbose|-v)                VERBOSE=true;                  shift   ;;
    --help|-h)                   usage; exit 0 ;;
    *) fatal "Unknown option: $1 — run with --help for usage" ;;
  esac
done

# ── Helpers ───────────────────────────────────────────────────────────────────
require_cmd() {
  command -v "$1" &>/dev/null || fatal "'$1' is not installed — please install it and retry"
}

# Run a command, suppressing output unless --verbose is set
q() { if $VERBOSE; then "$@"; else "$@" &>/dev/null; fi; }

# Install a .deb or .rpm, printing output only on failure
pkg_install() {
  local pkg="$1" label="$2"
  local out rc=0
  if [[ "$pkg_type" == "deb" ]]; then
    out=$(dpkg -i "$pkg" 2>&1) || rc=$?
  else
    out=$(rpm -U --replacefiles --replacepkgs "$pkg" 2>&1) || rc=$?
  fi
  $VERBOSE && printf "%s\n" "$out" || true
  [[ $rc -eq 0 ]] || fatal "${label} installation failed:\n${out}"
}

gh_api() {
  local url="$1"
  local args=(-fsSL -H "Accept: application/vnd.github.v3+json")
  [[ -n "$GITHUB_TOKEN" ]] && args+=(-H "Authorization: Bearer $GITHUB_TOKEN")
  curl "${args[@]}" "$url"
}

download() {
  local url="$1" dest="$2"
  local args=(-fSL --progress-bar)
  [[ -n "$GITHUB_TOKEN" ]] && args+=(-H "Authorization: Bearer $GITHUB_TOKEN")
  curl "${args[@]}" -o "$dest" "$url"
}

# ── Detection ─────────────────────────────────────────────────────────────────
detect_pkg_type() {
  [[ -f /etc/os-release ]] || fatal "Cannot detect Linux distribution — /etc/os-release not found"
  # shellcheck disable=SC1091
  . /etc/os-release
  case "${ID:-}" in
    ubuntu|debian)                            echo "deb"; return ;;
    rhel|centos|fedora|amzn|rocky|almalinux) echo "rpm"; return ;;
  esac
  case "${ID_LIKE:-}" in
    *debian*)        echo "deb"; return ;;
    *rhel*|*fedora*) echo "rpm"; return ;;
  esac
  fatal "Unsupported distribution: ${ID:-unknown} — open an issue at https://github.com/riptideslabs/daemon"
}

detect_distro_name() {
  # shellcheck disable=SC1091
  . /etc/os-release
  case "${ID:-}" in
    ubuntu)    echo "ubuntu" ;;
    debian)    echo "debian" ;;
    rhel)      echo "rhel${VERSION_ID%%.*}" ;;
    centos)    echo "centos${VERSION_ID%%.*}" ;;
    fedora)    echo "fedora${VERSION_ID}" ;;
    amzn)      echo "amazonlinux${VERSION_ID}" ;;
    rocky)     echo "rocky${VERSION_ID%%.*}" ;;
    almalinux) echo "almalinux${VERSION_ID%%.*}" ;;
    *)         echo "${ID:-linux}" ;;
  esac
}

detect_arch() {
  case "$(uname -m)" in
    x86_64)        echo "amd64" ;;
    aarch64|arm64) echo "arm64" ;;
    *) fatal "Unsupported architecture: $(uname -m)" ;;
  esac
}

is_ec2_instance() {
  # Try IMDSv2 first (recommended), fall back to IMDSv1
  local token
  token=$(curl -s -f --max-time 2 -X PUT "http://169.254.169.254/latest/api/token" \
    -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" 2>/dev/null)
  if [[ -n "$token" ]]; then
    curl -s -f --max-time 2 \
      -H "X-aws-ec2-metadata-token: $token" \
      "http://169.254.169.254/latest/meta-data/instance-id" &>/dev/null
    return $?
  fi
  curl -s -f --max-time 2 "http://169.254.169.254/latest/meta-data/instance-id" &>/dev/null
}

is_azure_instance() {
  curl -s -f --max-time 2 \
    -H "Metadata: true" \
    "http://169.254.169.254/metadata/instance?api-version=2021-02-01" &>/dev/null
}

is_gcp_instance() {
  curl -s -f --max-time 2 \
    -H "Metadata-Flavor: Google" \
    "http://metadata.google.internal/computeMetadata/v1/instance/id" &>/dev/null
}

resolve_version() {
  local repo="$1" override="${2:-latest}"
  if [[ "$override" == "latest" ]]; then
    local response
    response=$(gh_api "https://api.github.com/repos/${repo}/releases/latest") \
      || fatal "Could not fetch releases for ${repo} (HTTP error).\n  The repository may be private — set \$GITHUB_TOKEN or pass --github-token."
    echo "$response" | grep '"tag_name"' | sed 's/.*"tag_name": *"\([^"]*\)".*/\1/'
  else
    echo "$override"
  fi
}

# ── Already-installed info ────────────────────────────────────────────────────
show_installed_info() {
  local os_pretty kernel arch daemon_ver driver_ver svc_status
  os_pretty=$(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-unknown}")
  kernel=$(uname -r)
  arch=$(uname -m)
  daemon_ver=$(riptides --version 2>/dev/null | awk '/version/{print $3; exit}' || true)
  driver_ver=$(modinfo riptides 2>/dev/null | awk '/^version:/{print $2}' || true)
  svc_status=$(systemctl is-active riptides 2>/dev/null || true)

  printf "\n${BOLD}▶ Riptides is already installed${NC}\n\n"
  info "OS             : $os_pretty"
  info "Kernel         : $kernel"
  info "Architecture   : $arch"
  info "Daemon version : ${daemon_ver:-unknown}"
  if [[ -n "$driver_ver" ]]; then
    info "Driver version : $driver_ver"
  else
    warn "Driver version : not loaded"
  fi
  if [[ "$svc_status" == "active" ]]; then
    info "Service        : active"
  else
    warn "Service        : ${svc_status:-unknown}"
  fi
  info "Data directory : $DATA_DIR"
  printf "\n"
}

# ── Main ──────────────────────────────────────────────────────────────────────
main() {
  [[ $EUID -eq 0 ]] || fatal "Please run as root:  sudo -E bash install.sh ..."

  if command -v riptides &>/dev/null; then
    if modinfo riptides &>/dev/null; then
      if [[ "$(systemctl is-active riptides 2>/dev/null || true)" != "active" ]]; then
        step "Starting daemon service"
        systemctl start riptides \
          || fatal "Service failed to start — check logs with:  journalctl -u riptides -n 50"
        info "Service started"
      fi
      show_installed_info
      exit 0
    fi
    warn "Riptides daemon is installed but the driver module is missing — reinstalling driver"
  fi

  [[ -z "$CONTROL_PLANE" ]] && fatal "--controlplane-url is required"

  require_cmd curl
  require_cmd systemctl

  # ── Auto-detect auth method if none was given ────────────────────────────────
  if [[ -z "$USE_AWSIID" && -z "$USE_AZUREIMDS" && -z "$USE_GCPIIT" && -z "$USE_GITHUB_ACTIONS" && -z "$JOIN_TOKEN" ]]; then
    if [[ -n "${ACTIONS_ID_TOKEN_REQUEST_URL:-}" && -n "${ACTIONS_ID_TOKEN_REQUEST_TOKEN:-}" ]]; then
      info "GitHub Actions runner detected — using GitHub Actions OIDC authentication"
      USE_GITHUB_ACTIONS=1
    elif is_ec2_instance; then
      info "EC2 instance detected — using AWSIID authentication"
      USE_AWSIID=1
    elif is_azure_instance; then
      info "Azure VM detected — using Azure IMDS authentication"
      USE_AZUREIMDS=1
    elif is_gcp_instance; then
      info "GCP VM detected — using GCP Instance Identity Token authentication"
      USE_GCPIIT=1
    else
      fatal "Either --join-token TOKEN, --awsiid, --azureimds, --gcpiit, or --github-actions is required.\n  Pass an existing join token:\n    --join-token <token>\n  Or on EC2, use instance identity auth:\n    --awsiid\n  Or on Azure, use instance metadata auth:\n    --azureimds\n  Or on GCP, use instance identity token auth:\n    --gcpiit\n  Or in GitHub Actions, use OIDC auth:\n    --github-actions"
    fi
  fi

  # ── Detect system ───────────────────────────────────────────────────────────
  step "Detecting system"
  local pkg_type distro_name os_pretty arch kernel_version
  pkg_type=$(detect_pkg_type)
  distro_name=$(detect_distro_name)
  os_pretty=$(. /etc/os-release 2>/dev/null; echo "${PRETTY_NAME:-${ID:-unknown}}")
  arch=$(detect_arch)
  kernel_version=$(uname -r)
  info "Distribution : $distro_name ($os_pretty, $pkg_type)"
  info "Architecture : $arch"
  info "Kernel       : $kernel_version"

  # ── Resolve versions ────────────────────────────────────────────────────────
  step "Resolving versions"
  local daemon_version driver_loader_version
  daemon_version=$(resolve_version "riptides-packages/daemon" "$DAEMON_VERSION")
  [[ -n "$daemon_version" ]] || fatal "Could not resolve daemon version — check your network or set --github-token"
  driver_loader_version=$(resolve_version "riptides-packages/driver-loader" "latest")
  [[ -n "$driver_loader_version" ]] || fatal "Could not resolve driver-loader version — check your network or set --github-token"
  info "Daemon version        : $daemon_version"
  info "Driver loader version : $driver_loader_version"
  [[ -n "$DRIVER_VERSION" ]] && info "Driver version (pinned): $DRIVER_VERSION"

  local tmpdir=""
  tmpdir=$(mktemp -d)
  trap '[[ -n "${tmpdir:-}" ]] && rm -rf "$tmpdir"' EXIT

  # ── Driver loader (installs and loads the kernel driver) ────────────────────
  step "Installing driver loader"
  local loader_asset
  if [[ "$pkg_type" == "deb" ]]; then
    loader_asset="riptides-driver-loader_${driver_loader_version#v}_all.deb"
  else
    loader_asset="riptides-driver-loader-${driver_loader_version#v}-1.noarch.rpm"
  fi
  local loader_url="https://github.com/riptides-packages/driver-loader/releases/download/${driver_loader_version}/${loader_asset}"
  info "Downloading $loader_asset"
  download "$loader_url" "$tmpdir/$loader_asset"

  pkg_install "$tmpdir/$loader_asset" "Driver loader package"
  info "Driver loader installed"

  if [[ -n "$DRIVER_VERSION" ]]; then
    mkdir -p /etc/systemd/system/riptides-driver-loader.service.d
    printf '[Service]\nEnvironment=DRIVER_VERSION=%s\n' "$DRIVER_VERSION" \
      > /etc/systemd/system/riptides-driver-loader.service.d/version.conf
    q systemctl daemon-reload
  fi

  q systemctl enable riptides-driver-loader

  local jctl_pid=""
  if $VERBOSE; then
    journalctl -u riptides-driver-loader -f --since now --no-pager &
    jctl_pid=$!
  fi
  q systemctl restart --no-block riptides-driver-loader

  sleep 2
  _poll_loader() {
    while [[ "$(systemctl is-active riptides-driver-loader 2>/dev/null || true)" == "activating" ]]; do
      sleep 5
    done
  }
  with_spinner "Loading kernel driver — if we haven't seen kernel $(uname -r) before, we're building a driver for it now (this can take a few minutes)..." _poll_loader

  if [[ -n "$jctl_pid" ]]; then
    kill "$jctl_pid" 2>/dev/null || true
    wait "$jctl_pid" 2>/dev/null || true
    printf "\n"
  fi

  [[ "$(systemctl is-active riptides-driver-loader 2>/dev/null || true)" == "failed" ]] \
    && fatal "riptides-driver-loader.service failed — check: journalctl -u riptides-driver-loader -n 50"
  info "Driver loader service active"

  if ! systemctl list-unit-files riptides-modules.service &>/dev/null; then
    warn "riptides-modules.service not found — driver package may not have installed correctly"
    warn "Driver loader logs:"
    journalctl -u riptides-driver-loader -n 50 --no-pager >&2 || true
  else
    q systemctl enable --now riptides-modules
    systemctl is-active --quiet riptides-modules \
      || fatal "riptides-modules.service failed to start — check: journalctl -u riptides-modules -n 50"
    info "Driver service active"

    info "Waiting for kernel modules to load..."
    local mod_retries=0
    until lsmod | grep -q riptides; do
      (( mod_retries++ )) || true
      [[ $mod_retries -ge 30 ]] && { warn "Kernel modules not loaded after 30s — check: systemctl status riptides-modules"; break; }
      sleep 1
    done
    lsmod | grep -q riptides && info "Kernel modules active" || true
  fi

  # ── Daemon package ──────────────────────────────────────────────────────────
  step "Installing daemon"
  local daemon_asset="riptides-daemon_${daemon_version#v}_linux_${arch}.${pkg_type}"
  local daemon_url="https://github.com/riptides-packages/daemon/releases/download/${daemon_version}/${daemon_asset}"
  info "Downloading $daemon_asset"
  download "$daemon_url" "$tmpdir/$daemon_asset"

  pkg_install "$tmpdir/$daemon_asset" "Daemon package"
  info "Daemon installed"

  # ── Configuration ───────────────────────────────────────────────────────────
  step "Configuring daemon"

  local auth_args=(
    --controlplane-url "$CONTROL_PLANE"
    --data-dir         "$DATA_DIR"
    --non-interactive
  )
  [[ -n "$JOIN_TOKEN" ]]               && auth_args+=(--join-token                "$JOIN_TOKEN")
  # Shorthand flags map to --plugin for explicit selection; --plugin overrides if both given
  [[ -n "$USE_AWSIID" ]]               && auth_args+=(--plugin                    "AWSIID")
  [[ -n "$USE_AZUREIMDS" ]]            && auth_args+=(--plugin                    "AzureIMDS")
  [[ -n "$USE_GCPIIT" ]]               && auth_args+=(--plugin                    "GCPIIT")
  [[ -n "$USE_GITHUB_ACTIONS" ]]       && auth_args+=(--plugin                    "GitHubActions")
  [[ -n "$PLUGIN" ]]                   && auth_args+=(--plugin                    "$PLUGIN")
  [[ -n "$AZUREIMDS_RESOURCE" ]]       && auth_args+=(--azureimds-resource        "$AZUREIMDS_RESOURCE")
  [[ -n "$GCPIIT_AUDIENCE" ]]          && auth_args+=(--gcpiit-audience           "$GCPIIT_AUDIENCE")
  [[ -n "$GITHUB_ACTIONS_AUDIENCE" ]]  && auth_args+=(--github-actions-audience   "$GITHUB_ACTIONS_AUDIENCE")
  [[ -n "$K8SSAT_CLUSTER_ID" ]]        && auth_args+=(--k8ssat-cluster-id         "$K8SSAT_CLUSTER_ID")
  [[ -n "$K8SSAT_TOKEN_PATH" ]]        && auth_args+=(--k8ssat-token-path         "$K8SSAT_TOKEN_PATH")
  [[ -n "$JWT_ISSUER" ]]               && auth_args+=(--jwt-issuer                "$JWT_ISSUER")
  [[ -n "$JWT_TOKEN_PATH" ]]           && auth_args+=(--jwt-token-path            "$JWT_TOKEN_PATH")
  [[ -n "$SSHCERTPOP_KEY_PATH" ]]      && auth_args+=(--sshcertpop-key-path       "$SSHCERTPOP_KEY_PATH")
  [[ -n "$SSHCERTPOP_CERT_PATH" ]]     && auth_args+=(--sshcertpop-cert-path      "$SSHCERTPOP_CERT_PATH")
  [[ -n "$X509CERTPOP_KEY_PATH" ]]     && auth_args+=(--x509certpop-key-path      "$X509CERTPOP_KEY_PATH")
  [[ -n "$X509CERTPOP_CERT_PATH" ]]    && auth_args+=(--x509certpop-cert-path     "$X509CERTPOP_CERT_PATH")

  riptides daemon auth "${auth_args[@]}" \
    || fatal "Authentication failed — check your control plane URL and credentials"
  info "Authenticated to $CONTROL_PLANE"

  # ── Service ─────────────────────────────────────────────────────────────────
  step "Starting daemon service"
  q systemctl enable riptides
  q systemctl start  riptides
  systemctl is-active --quiet riptides && info "Service started successfully" \
    || fatal "Service failed to start — check logs with:  journalctl -u riptides -n 50"

  # ── Uninstall script ────────────────────────────────────────────────────────
  step "Installing uninstall script"
  curl -fsSL "https://docs.riptides.io/uninstall.sh" -o /usr/local/bin/riptides-uninstall.sh \
    && chmod +x /usr/local/bin/riptides-uninstall.sh \
    && info "Uninstall script installed at /usr/local/bin/riptides-uninstall.sh" \
    || warn "Could not install uninstall script — run: curl -fsSL https://docs.riptides.io/uninstall.sh | sudo bash"

  # ── Done ────────────────────────────────────────────────────────────────────
  local installed_driver_version
  installed_driver_version=$(modinfo riptides 2>/dev/null | awk '/^version:/{print $2}' || true)

  printf "\n${GREEN}${BOLD}  Installation complete!${NC}\n\n"
  printf "  Control plane  : %s\n"   "$CONTROL_PLANE"
  printf "  OS             : %s\n"   "$os_pretty"
  local auth_method="joinToken"
  [[ -n "$USE_AWSIID" ]]          && auth_method="AWSIID (EC2 instance identity)"
  [[ -n "$USE_AZUREIMDS" ]]       && auth_method="azure-imds (Azure VM instance metadata)"
  [[ -n "$USE_GCPIIT" ]]          && auth_method="gcpiit (GCP instance identity token)"
  [[ -n "$USE_GITHUB_ACTIONS" ]]  && auth_method="github-actions (GitHub Actions OIDC)"
  printf "  Auth method    : %s\n"   "$auth_method"
  printf "  Daemon version : %s\n"   "$daemon_version"
  printf "  Driver version : %s\n"   "${installed_driver_version:-unknown}"
  printf "  Data directory : %s\n\n" "$DATA_DIR"
  printf "  Next steps:\n"
  printf "    Check status   →  systemctl status riptides\n"
  printf "    Follow logs    →  journalctl -u riptides -f\n"
  printf "    Uninstall      →  sudo riptides-uninstall.sh\n\n"
}

main
