#!/usr/bin/env bash
# Growexia — installation d'un produit sur un serveur client (docs/platform/06-updates-and-operations.md §8, §9).
#
#   curl -fsSL https://get.growexia.com/install.sh | sudo bash -s -- --product DROGUERIE --token GX-ENROLL-XXXX
#   sudo ./install.sh --offline site_7f3c-droguerie-1.5.0.gxb --passphrase-file pass.txt
#
# Writes <dir>/compose.yml (bootstrap: growexia-agent only) and <dir>/.env, then starts the agent. The agent
# enrolls, installs the product release and from then on owns compose.yml/.env. Safe to re-run.
set -euo pipefail

# Replaced by the Hub when served from GET /install.sh.
DEFAULT_HUB_URL="https://hub.growexia.com"
# Split so the Hub's substitution of the placeholder above does not also rewrite this check.
PLACEHOLDER="__GX_HUB""_URL__"
DEFAULT_AGENT_IMAGE="registry.growexia.com/platform/agent:latest"
BOOTSTRAP_MARKER="# growexia-bootstrap"
MIN_DOCKER_MAJOR=24
MIN_MEM_KB=$((2 * 1024 * 1024))
MIN_DISK_KB=$((20 * 1024 * 1024))
MEMINFO="${GX_MEMINFO:-/proc/meminfo}"

PRODUCT=""
TOKEN=""
HUB=""
DIR=""
OFFLINE=""
PASSFILE=""
YES=0
AGENT_IMAGE=""
AGENT_IMAGE_EXPLICIT=""
PROJECT_OPT=""
HUB_EXPLICIT=""
SETS=()
SECRETS=()

say() { printf '%s\n' "$*"; }
ok() { printf '  [ok] %s\n' "$*"; }
warn() { printf '  [attention] %s\n' "$*" >&2; WARNINGS=$((WARNINGS + 1)); }
warn_nonblocking() { printf '  [attention] %s\n' "$*" >&2; }
die() { printf 'ERREUR : %s\n' "$*" >&2; exit 1; }
WARNINGS=0

usage() {
  cat <<'EOF'
Usage : install.sh --product <CODE> --token <GX-ENROLL-…> [options]
        install.sh --offline <bundle.gxb> --passphrase-file <fichier> [options]

  --product <CODE>          code produit (DROGUERIE, FLEET…) ; lu dans le bundle en mode hors ligne
  --token <TOKEN>           jeton d'enrôlement (24 h, à usage unique) ; inutile pour relancer l'installation
  --hub <url>               URL du Hub (défaut : celle du Hub qui a servi ce script)
  --dir <dossier>           dossier du projet (défaut : /opt/growexia/<produit>)
  --offline <fichier.gxb>   installation sans réseau à partir d'un bundle hors ligne
  --passphrase-file <f>     fichier contenant la phrase de passe du bundle
  --agent-image <ref>       image de l'agent (défaut : registry.growexia.com/platform/agent:latest)
  --project <nom>           nom du projet compose (défaut : code produit en minuscules) ; deux sites du même
                            produit sur une même machine (tests) doivent avoir des noms différents
  --set <CLÉ=valeur>        réglage du site écrit dans .env (répétable), ex. --set DROG_DOMAIN=caisse.client.ma
  --secret <CLÉ>            secret généré au hasard dans .env s'il n'y est pas déjà (répétable) ;
                            jamais affiché ni envoyé au Hub : grep '^CLÉ=' <dossier>/.env pour le lire
  --yes                     continuer malgré les avertissements (RAM, disque, NTP)
  -h, --help                cette aide

Variable : GX_HUB_INSECURE=1 autorise un Hub en http:// (tests uniquement).
EOF
}

while [ $# -gt 0 ]; do
  case "$1" in
    --product) PRODUCT="${2:-}"; shift 2 ;;
    --token) TOKEN="${2:-}"; shift 2 ;;
    --hub) HUB="${2:-}"; HUB_EXPLICIT=1; shift 2 ;;
    --dir) DIR="${2:-}"; shift 2 ;;
    --offline) OFFLINE="${2:-}"; shift 2 ;;
    --passphrase-file) PASSFILE="${2:-}"; shift 2 ;;
    --agent-image) AGENT_IMAGE="${2:-}"; AGENT_IMAGE_EXPLICIT=1; shift 2 ;;
    --project) PROJECT_OPT="${2:-}"; shift 2 ;;
    --set) SETS+=("${2:-}"); shift 2 ;;
    --secret) SECRETS+=("${2:-}"); shift 2 ;;
    --yes|-y) YES=1; shift ;;
    -h|--help) usage; exit 0 ;;
    *) usage >&2; die "option inconnue : $1" ;;
  esac
done

json_field() { # json_field <key> <json> : string value of a top-level key in compact JSON
  printf '%s' "$2" | sed -n "s/.*\"$1\":\"\\([^\"]*\\)\".*/\\1/p" | head -n 1
}

# ---------------------------------------------------------------- arguments

BUNDLE_JSON=""
if [ -n "$OFFLINE" ]; then
  [ -f "$OFFLINE" ] || die "bundle introuvable : $OFFLINE"
  [ -n "$PASSFILE" ] || die "--offline nécessite --passphrase-file <fichier>"
  [ -r "$PASSFILE" ] || die "fichier de phrase de passe illisible : $PASSFILE"
  BUNDLE_JSON="$(tar -xOf "$OFFLINE" bundle.json 2>/dev/null)" || die "fichier non reconnu comme bundle Growexia (bundle.json absent) : $OFFLINE"
  BUNDLE_PRODUCT="$(json_field product "$BUNDLE_JSON")"
  [ -n "$BUNDLE_PRODUCT" ] || die "bundle.json sans produit : $OFFLINE"
  if [ -n "$PRODUCT" ] && [ "$(printf '%s' "$PRODUCT" | tr '[:lower:]' '[:upper:]')" != "$BUNDLE_PRODUCT" ]; then
    die "le bundle est pour $BUNDLE_PRODUCT, pas pour $PRODUCT"
  fi
  PRODUCT="$BUNDLE_PRODUCT"
  if [ -z "$AGENT_IMAGE" ]; then
    AGENT_IMAGE="$(json_field agentImage "$BUNDLE_JSON")"
    AGENT_IMAGE_EXPLICIT=1 # the image loaded from the bundle is the one to run
  fi
  [ -n "$HUB" ] || HUB="$(json_field hubUrl "$BUNDLE_JSON")"
  [ -z "$TOKEN" ] || die "--token et --offline sont incompatibles (l'identité du site est dans le bundle)"
fi

[ -n "$PRODUCT" ] || { usage >&2; die "--product est obligatoire"; }
PRODUCT="$(printf '%s' "$PRODUCT" | tr '[:lower:]' '[:upper:]')"
printf '%s' "$PRODUCT" | grep -Eq '^[A-Z][A-Z0-9_-]{1,31}$' || die "code produit invalide : $PRODUCT"
PROJECT="${PROJECT_OPT:-$(printf '%s' "$PRODUCT" | tr '[:upper:]_' '[:lower:]-')}"
printf '%s' "$PROJECT" | grep -Eq '^[a-z0-9][a-z0-9_-]{0,62}$' || die "nom de projet invalide : $PROJECT"
[ -n "$DIR" ] || DIR="/opt/growexia/$PROJECT"
case "$DIR" in /*) ;; *) die "--dir doit être un chemin absolu : $DIR" ;; esac

site_key_ok() { # product settings only: GX_* and COMPOSE_* belong to the installer and the agent
  printf '%s' "$1" | grep -Eq '^[A-Z][A-Z0-9_]{0,63}$' || return 1
  case "$1" in GX_*|COMPOSE_*) return 1 ;; esac
}
for kv in ${SETS[@]+"${SETS[@]}"}; do
  case "$kv" in *=*) ;; *) die "--set attend CLÉ=valeur : $kv" ;; esac
  site_key_ok "${kv%%=*}" || die "clé invalide pour --set : ${kv%%=*} (majuscules, chiffres, _ ; GX_* et COMPOSE_* réservées)"
  case "$kv" in *$'\n'*) die "--set : valeur sur une seule ligne" ;; esac
done
for k in ${SECRETS[@]+"${SECRETS[@]}"}; do
  site_key_ok "$k" || die "clé invalide pour --secret : $k (majuscules, chiffres, _ ; GX_* et COMPOSE_* réservées)"
done
DIR="${DIR%/}"
[ -n "$AGENT_IMAGE" ] || AGENT_IMAGE="$DEFAULT_AGENT_IMAGE"
if [ -z "$HUB" ] && [ -f "$DIR/.env" ]; then
  HUB="$(sed -n 's/^GX_HUB_URL=//p' "$DIR/.env" | tail -n 1)" # re-run: keep the site's Hub
fi
[ -n "$HUB" ] || HUB="$DEFAULT_HUB_URL"
HUB="${HUB%/}"
[ "$HUB" != "$PLACEHOLDER" ] || HUB=""
INSECURE=false
case "${GX_HUB_INSECURE:-}" in 1|true|TRUE|yes) INSECURE=true ;; esac
if [ -z "$OFFLINE" ]; then
  case "$HUB" in
    "") die "URL du Hub inconnue : précisez --hub https://hub.growexia.com (ou téléchargez le script depuis le Hub)" ;;
    https://*) ;;
    http://*) [ "$INSECURE" = true ] || die "le Hub doit être en https:// ($HUB) ; GX_HUB_INSECURE=1 uniquement pour les tests" ;;
    *) die "URL du Hub invalide : $HUB" ;;
  esac
fi
if [ -n "$TOKEN" ]; then
  if [ "${#TOKEN}" -lt 8 ] || [ "${#TOKEN}" -gt 256 ] || ! printf '%s' "$TOKEN" | grep -Eq '^[A-Za-z0-9._~-]+$'; then
    die "jeton d'enrôlement invalide"
  fi
fi

# ---------------------------------------------------------------- preflight

say "Growexia — installation de $PRODUCT dans $DIR"
say "Vérifications préalables :"

# GX_INSTALL_ALLOW_NON_ROOT=1: local development only (Docker Desktop, where the user owns the docker
# socket). Never on a client server.
if [ "$(id -u)" = "0" ]; then
  ok "root"
elif [ "${GX_INSTALL_ALLOW_NON_ROOT:-0}" = "1" ]; then
  warn_nonblocking "exécution sans root (GX_INSTALL_ALLOW_NON_ROOT=1, développement local uniquement)"
else
  die "ce script doit être exécuté en root (sudo)"
fi

command -v docker >/dev/null 2>&1 || die "Docker n'est pas installé (Docker Engine $MIN_DOCKER_MAJOR ou plus requis : https://docs.docker.com/engine/install/)"
DOCKER_VERSION="$(docker version --format '{{.Server.Version}}' 2>/dev/null)" \
  || die "le démon Docker ne répond pas (systemctl start docker ?)"
DOCKER_MAJOR="${DOCKER_VERSION%%.*}"
case "$DOCKER_MAJOR" in ''|*[!0-9]*) die "version de Docker illisible : $DOCKER_VERSION" ;; esac
[ "$DOCKER_MAJOR" -ge "$MIN_DOCKER_MAJOR" ] || die "Docker $DOCKER_VERSION est trop ancien : version $MIN_DOCKER_MAJOR ou plus requise"
ok "Docker $DOCKER_VERSION"

COMPOSE_VERSION="$(docker compose version --short 2>/dev/null)" \
  || die "le plugin docker compose est absent (paquet docker-compose-plugin)"
ok "docker compose $COMPOSE_VERSION"

if [ -r "$MEMINFO" ]; then
  MEM_KB="$(awk '/^MemAvailable:/ {print $2}' "$MEMINFO")"
  if [ -n "$MEM_KB" ] && [ "$MEM_KB" -lt "$MIN_MEM_KB" ]; then
    warn "mémoire disponible insuffisante : $((MEM_KB / 1024)) Mo (2 Go minimum)"
  else
    ok "mémoire disponible $(( ${MEM_KB:-0} / 1024 )) Mo"
  fi
else
  warn "impossible de lire $MEMINFO pour vérifier la mémoire"
fi

PROBE="$DIR"
while [ ! -d "$PROBE" ]; do PROBE="$(dirname "$PROBE")"; done
DISK_KB="$(df -Pk "$PROBE" | awk 'NR==2 {print $4}')"
if [ -n "$DISK_KB" ] && [ "$DISK_KB" -lt "$MIN_DISK_KB" ]; then
  warn "espace disque insuffisant sur $PROBE : $((DISK_KB / 1024 / 1024)) Go libres (20 Go minimum)"
else
  ok "disque : $(( ${DISK_KB:-0} / 1024 / 1024 )) Go libres"
fi

if command -v timedatectl >/dev/null 2>&1; then
  NTP="$(timedatectl show -p NTPSynchronized --value 2>/dev/null || true)"
  if [ "$NTP" = "yes" ]; then
    ok "horloge synchronisée (NTP)"
  else
    warn "horloge non synchronisée : activez NTP (timedatectl set-ntp true), sinon les échanges avec le Hub peuvent être refusés"
  fi
else
  warn "timedatectl absent : vérifiez que l'horloge est synchronisée (NTP)"
fi

if [ "$WARNINGS" -gt 0 ] && [ "$YES" != 1 ]; then
  die "$WARNINGS avertissement(s) ci-dessus. Corrigez-les, ou relancez avec --yes pour continuer quand même"
fi

# ---------------------------------------------------------------- files

mkdir -p "$DIR"
chmod 755 "$DIR"
ENV_FILE="$DIR/.env"
COMPOSE_FILE="$DIR/compose.yml"

if [ ! -f "$ENV_FILE" ] && [ -z "$TOKEN" ] && [ -z "$OFFLINE" ]; then
  die "--token est obligatoire pour une première installation (jeton émis par le Hub, page du site)"
fi

set_env() { # set_env <key> <value> : replace or append, every other line kept as is
  local key="$1" value="$2" tmp
  tmp="$(mktemp "$DIR/.env.XXXXXX")"
  if [ -f "$ENV_FILE" ]; then
    awk -v k="$key" -v v="$value" 'BEGIN { done = 0 }
      $0 ~ "^" k "=" { if (!done) { print k "=" v; done = 1 }; next }
      { print }
      END { if (!done) print k "=" v }' "$ENV_FILE" > "$tmp"
  else
    printf '%s=%s\n' "$key" "$value" > "$tmp"
  fi
  chmod 600 "$tmp"
  mv "$tmp" "$ENV_FILE"
}

if [ ! -f "$ENV_FILE" ]; then
  printf '# Growexia %s — site configuration. The agent adds GX_IMAGE_* values; keep the other keys.\n' "$PRODUCT" > "$ENV_FILE"
  chmod 600 "$ENV_FILE"
fi
set_env COMPOSE_PROJECT_NAME "$PROJECT"
set_env GX_PRODUCT "$PRODUCT"
if [ -n "$HUB" ] && { [ -n "$HUB_EXPLICIT" ] || ! grep -q '^GX_HUB_URL=' "$ENV_FILE"; }; then
  set_env GX_HUB_URL "$HUB"
fi
if [ -n "${GX_HUB_INSECURE:-}" ] || ! grep -q '^GX_HUB_INSECURE=' "$ENV_FILE"; then
  set_env GX_HUB_INSECURE "$INSECURE"
fi
set_env GX_PROJECT_HOST_DIR "$DIR"
set_env GX_HOSTNAME "$(hostname 2>/dev/null || echo unknown)"
[ -z "$TOKEN" ] || set_env GX_ENROLL_TOKEN "$TOKEN"
# The agent image: only set when absent, or when asked explicitly (releases manage it afterwards).
if ! grep -q '^GX_IMAGE_GROWEXIA_AGENT=' "$ENV_FILE" || [ -n "$AGENT_IMAGE_EXPLICIT" ]; then
  set_env GX_IMAGE_GROWEXIA_AGENT "$AGENT_IMAGE"
fi
for kv in ${SETS[@]+"${SETS[@]}"}; do
  set_env "${kv%%=*}" "${kv#*=}"
done
random_secret() { # 40 characters [A-Za-z0-9] from the kernel CSPRNG
  LC_ALL=C tr -dc 'A-Za-z0-9' < /dev/urandom | head -c 40
}
GENERATED=""
for k in ${SECRETS[@]+"${SECRETS[@]}"}; do
  if ! grep -Eq "^$k=.+" "$ENV_FILE"; then
    set_env "$k" "$(random_secret)"
    GENERATED="$GENERATED $k"
  fi
done
ok ".env écrit ($ENV_FILE)"
[ -z "$GENERATED" ] || ok "secrets générés dans .env :$GENERATED (lecture : grep '^CLÉ=' $ENV_FILE)"

MACHINE_ID_MOUNT=""
[ ! -f /etc/machine-id ] || MACHINE_ID_MOUNT="      - /etc/machine-id:/etc/machine-id:ro"

if [ -f "$COMPOSE_FILE" ] && ! grep -q "^$BOOTSTRAP_MARKER" "$COMPOSE_FILE"; then
  ok "compose.yml existant conservé (version installée par l'agent)"
else
  cat > "$COMPOSE_FILE.tmp" <<EOF
$BOOTSTRAP_MARKER: written by install.sh, replaced by the first release the agent installs.
name: \${COMPOSE_PROJECT_NAME}

services:
  growexia-agent:
    image: \${GX_IMAGE_GROWEXIA_AGENT}
    restart: unless-stopped
    environment:
      GX_HUB_URL: \${GX_HUB_URL:-}
      GX_HUB_INSECURE: \${GX_HUB_INSECURE:-false}
      GX_PRODUCT: \${GX_PRODUCT}
      GX_ENROLL_TOKEN: \${GX_ENROLL_TOKEN:-}
      GX_HOSTNAME: \${GX_HOSTNAME:-}
      GX_PROJECT_HOST_DIR: \${GX_PROJECT_HOST_DIR}
      GX_BACKUP_CMD: \${GX_BACKUP_CMD:-}
      GX_BACKUP_RUN_CMD: \${GX_BACKUP_RUN_CMD:-}
    volumes:
      - growexia-lease:/run/growexia
      - growexia-agent-state:/state
      - /var/run/docker.sock:/var/run/docker.sock
      - $DIR:/project
$MACHINE_ID_MOUNT

volumes:
  growexia-lease:
  growexia-agent-state:
EOF
  chmod 644 "$COMPOSE_FILE.tmp"
  mv "$COMPOSE_FILE.tmp" "$COMPOSE_FILE"
  ok "compose.yml d'amorçage écrit ($COMPOSE_FILE)"
fi

compose() { docker compose -p "$PROJECT" -f "$COMPOSE_FILE" --env-file "$ENV_FILE" --project-directory "$DIR" "$@"; }

# ---------------------------------------------------------------- start

if [ -n "$OFFLINE" ]; then
  OFFLINE_ABS="$(cd "$(dirname "$OFFLINE")" && pwd)/$(basename "$OFFLINE")"
  PASS_ABS="$(cd "$(dirname "$PASSFILE")" && pwd)/$(basename "$PASSFILE")"
  say "Chargement des images du bundle (peut prendre plusieurs minutes)…"
  tar -xOf "$OFFLINE_ABS" images.tar | docker load -q || die "échec du chargement des images (docker load)"
  ok "images chargées"
  say "Installation hors ligne…"
  compose run --rm -T --no-deps \
    -v "$OFFLINE_ABS:/tmp/growexia-bundle.gxb:ro" -v "$PASS_ABS:/tmp/growexia-passphrase:ro" \
    growexia-agent import /tmp/growexia-bundle.gxb --passphrase-file /tmp/growexia-passphrase --no-load \
    || die "l'import du bundle a échoué (voir les messages ci-dessus)"
  ok "produit installé depuis le bundle"
else
  say "Téléchargement de l'agent…"
  compose pull -q growexia-agent || die "impossible de télécharger $AGENT_IMAGE (accès à registry.growexia.com ?)"
fi

compose up -d growexia-agent || die "le démarrage de l'agent a échoué"
ok "agent démarré"

say ""
if [ -n "$OFFLINE" ]; then
  say "Installation hors ligne terminée : $PRODUCT tourne avec la licence du bundle, sans connexion au Hub."
else
  say "Installation lancée. L'agent s'enrôle auprès du Hub puis installe $PRODUCT (quelques minutes)."
fi
say "Suivi :  docker compose -p $PROJECT -f $COMPOSE_FILE logs -f growexia-agent"
say "État  :  docker compose -p $PROJECT -f $COMPOSE_FILE exec growexia-agent agent status"
