#!/usr/bin/env bash
# RDT agent installer for Linux (Debian/Ubuntu/Mint, x86_64/arm64).
#
#   curl -fsSL https://rdt-test.pages.dev/install.sh | bash
#
# Environment:
#   RDT_DOMAIN=rdt-test.pages.dev   deployment domain (Cloudflare Pages)
#   RDT_DEPLOY_CODE="1234 ..."      20 digit deployment code (required)
#   RDT_DEMO=1                      use the public demo deployment code
#   RDT_DEVICE_CODE="1234 ..."      force a device code (default: generated)
#   RDT_SLUG="perso@id"             group slug for the web dashboard
#   RDT_INDEX=1                     device number inside the slug
#   RDT_UNATTENDED=1                no local approval (VPS/VM)
#   RDT_TERMINAL=1                  enable the web terminal
#   RDT_BASE_URL=https://.../download  binary mirror (default: the Page itself)
#   RDT_PREFIX=~/.local             install prefix
#   RDT_NO_SERVICE=1                do not install the systemd user service
set -euo pipefail

PREFIX="${RDT_PREFIX:-$HOME/.local}"
BIN_DIR="$PREFIX/bin"
DOMAIN="${RDT_DOMAIN:-rdt-test.pages.dev}"
DEPLOY="${RDT_DEPLOY_CODE:-}"
DEMO="${RDT_DEMO:-0}"
DEMO_CODE="73419920558310476628"

say() { printf '  %s\n' "$*"; }
die() { printf '\n  Erreur : %s\n' "$*" >&2; exit 1; }
need() { command -v "$1" >/dev/null 2>&1 || die "$1 est requis"; }
need curl
need uname

if [ -z "$DEPLOY" ]; then
  if [ "$DEMO" = "1" ]; then
    DEPLOY="$DEMO_CODE"
  else
    cat <<EOF

  Code de déploiement manquant.

  Il se trouve dans GitLab CI/CD → « Generate codes » (artefact
  rdt-codes-secret) ou dans readme-code.txt de votre fork. Pour essayer la
  démonstration publique :

    RDT_DEMO=1 bash install.sh

  Pour votre déploiement :

    RDT_DOMAIN=votre-domaine.pages.dev \\
    RDT_DEPLOY_CODE="1234 5678 9012 3456 7890" \\
    bash install.sh

EOF
    exit 1
  fi
fi

[ "$(uname -s)" = "Linux" ] || die "ce script ne prend en charge que Linux (Windows : install.ps1)"

case "$(uname -m)" in
  x86_64|amd64) ARCH=amd64 ;;
  aarch64|arm64) ARCH=arm64 ;;
  *) die "architecture non prise en charge : $(uname -m)" ;;
esac

# Binaries are served by the same Cloudflare Pages deployment as this script.
# This deliberately avoids any dependency on a GitHub/GitLab account API.
BASE="${RDT_BASE_URL:-https://$DOMAIN/download}"
URL="$BASE/rdt-agent-linux-$ARCH"

TMP="$(mktemp -d)"
trap 'rm -rf "$TMP"' EXIT

echo
echo "  RDT — installation de l'agent ($ARCH)"
echo

say "Téléchargement de $URL"
curl -fL --proto '=https' --tlsv1.2 --retry 3 --connect-timeout 15 -o "$TMP/rdt-agent" "$URL" \
  || die "téléchargement impossible (release absente ou réseau bloqué)"

if curl -fsL --proto '=https' --tlsv1.2 -o "$TMP/rdt-agent.sha256" "$URL.sha256" 2>/dev/null; then
  EXPECTED="$(awk '{print $1}' "$TMP/rdt-agent.sha256" | head -n1)"
  if command -v sha256sum >/dev/null 2>&1; then
    ACTUAL="$(sha256sum "$TMP/rdt-agent" | awk '{print $1}')"
  else
    ACTUAL="$(shasum -a 256 "$TMP/rdt-agent" | awk '{print $1}')"
  fi
  [ "$EXPECTED" = "$ACTUAL" ] || die "somme SHA-256 invalide (téléchargement corrompu)"
  say "SHA-256 vérifié"
else
  say "Attention : pas de somme SHA-256 publiée, poursuite sans vérification"
fi

chmod +x "$TMP/rdt-agent"
mkdir -p "$BIN_DIR"
install -m 0755 "$TMP/rdt-agent" "$BIN_DIR/rdt-agent"
say "Binaire installé : $BIN_DIR/rdt-agent"

# The deployment domain tells us which relay to use.  A custom deployment can
# override it with RDT_RELAY.
RELAY="${RDT_RELAY:-}"
if [ -z "$RELAY" ]; then
  CONFIG_JSON="$(curl -fsSL --proto '=https' --max-time 15 "https://$DOMAIN/config.json" || true)"
  RELAY="$(printf '%s' "$CONFIG_JSON" | sed -n 's/.*"relay"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)"
fi
[ -n "$RELAY" ] || RELAY="wss://rdt-signal.chell-discord-officiel.workers.dev/ws"
say "Relais : $RELAY"

CONFIGURE=(configure --domain "$DOMAIN" --deploy-code "$DEPLOY" --relay "$RELAY")
if [ -n "${RDT_SLUG:-}" ]; then
  CONFIGURE+=(--slug "$RDT_SLUG" --index "${RDT_INDEX:-1}")
fi
[ -n "${RDT_DEVICE_CODE:-}" ] && CONFIGURE+=(--device-code "$RDT_DEVICE_CODE")
[ "${RDT_UNATTENDED:-0}" = "1" ] && CONFIGURE+=(--unattended)
[ "${RDT_TERMINAL:-0}" = "1" ] && CONFIGURE+=(--terminal)
"$BIN_DIR/rdt-agent" "${CONFIGURE[@]}"

case ":$PATH:" in
  *":$BIN_DIR:"*) ;;
  *) say "Ajoutez $BIN_DIR à votre PATH :"
     say "  echo 'export PATH=\"\$HOME/.local/bin:\$PATH\"' >> ~/.profile" ;;
esac

if [ "${RDT_NO_SERVICE:-0}" != "1" ]; then
  if command -v systemctl >/dev/null 2>&1; then
    "$BIN_DIR/rdt-agent" install || {
      echo
      say "Le service n'a pas pu démarrer automatiquement."
      say "Lancez l'agent dans votre session graphique :"
      say "  $BIN_DIR/rdt-agent run"
    }
  else
    say "systemd introuvable : lancez l'agent manuellement :"
    say "  $BIN_DIR/rdt-agent run"
  fi
else
  say "Service non installé (RDT_NO_SERVICE=1)."
  say "Lancez : $BIN_DIR/rdt-agent run"
fi

echo
"$BIN_DIR/rdt-agent" code 2>/dev/null || true
echo
say "Connectez-vous sur https://$DOMAIN avec le code de déploiement et le code appareil."
say "Site vitrine : https://remote-desktop-tool.pages.dev"
say "Journaux : journalctl --user -u rdt-agent -f"
echo
