#!/usr/bin/env bash
# Danke OS Agent : lance le fork de CasaOS et le module Hermes, sans root.
#   danke-os start | stop | restart | status | logs [service] | open
# Tout vit dans $DANKE_OS_HOME (par défaut ~/.local/share/danke-os) ; rien n'est écrit dans /etc ni /var.
set -uo pipefail

SELF="$(readlink -f "$0")"
ROOT="$(cd "$(dirname "$SELF")/.." && pwd)"
BIN="$ROOT/dist/bin"
H="${DANKE_OS_HOME:-$HOME/.local/share/danke-os}"
# réglages permanents (ex. DANKE_OS_BIND=0.0.0.0 pour le réseau local) ; l'environnement garde la priorité
if [ -f "$H/etc/danke-os.env" ]; then
  while IFS='=' read -r k v; do
    case "$k" in DANKE_OS_*) [ -n "${!k:-}" ] || export "$k=$v" ;; esac
  done < <(grep -E '^DANKE_OS_[A-Z_]+=' "$H/etc/danke-os.env")
fi
PORT="${DANKE_OS_PORT:-7130}"
export DANKE_OS_HOME="$H"
export CASAOS_CONFIG_PATH="$H/etc"
# dossiers des apps (les catalogues visent /DATA, impossible à créer sans root)
export DANKE_OS_DATA="${DANKE_OS_DATA:-$H/DATA}"

SERVICES=(gateway message-bus user-service local-storage app-management casaos danke-hermes)

conf() { # conf <fichier> <contenu> : n'écrase jamais une config existante
  [ -e "$H/etc/$1" ] || printf '%s\n' "$2" > "$H/etc/$1"
}

prepare() {
  mkdir -p "$H"/{etc,run,run/pids,log,db,conf,apps,appstore,www,shell,data}
  chmod 700 "$H"
  conf gateway.ini "[common]
runtimepath=$H/run

[gateway]
port=$PORT
LogPath=$H/log
LogSaveName=gateway
LogFileExt=log"
  conf message-bus.conf "[common]
RuntimePath=$H/run

[app]
LogPath=$H/log
LogSaveName=message-bus
LogFileExt=log
DBPath=$H"
  conf user-service.conf "[common]
RuntimePath=$H/run

[app]
LogPath=$H/log
LogSaveName=user-service
LogFileExt=log
DBPath=$H/db
UserDataPath=$H"
  conf local-storage.conf "[common]
RuntimePath=$H/run

[app]
LogPath=$H/log
LogSaveName=local-storage
LogFileExt=log
DBPath=$H/db
ShellPath=$H/shell

[server]
USBAutoMount=False
EnableMergerFS=false"
  conf app-management.conf "[common]
RuntimePath=$H/run

[app]
LogPath=$H/log
LogSaveName=app-management
LogFileExt=log
AppStorePath=$H/appstore
AppsPath=$H/apps

[server]
appstore=https://cdn.jsdelivr.net/gh/IceWhaleTech/CasaOS-AppStore@gh-pages/store/main.zip"
  conf casaos.conf "[app]
PAGE_SIZE=10
RuntimeRootPath=runtime/
LogPath=$H/log
LogSaveName=casaos
LogFileExt=log
DateStrFormat=20060102
DateTimeFormat=2006-01-02 15:04:05
TimeFormat=15:04:05
DateFormat=2006-01-02
DBPath=$H
ShellPath=$H/shell
UserDataPath=$H/conf

[common]
RuntimePath=$H/run

[server]
RunMode=release
USBAutoMount=False"
  [ -e "$H/shell/helper.sh" ] || cp -r "$ROOT"/CasaOS/build/sysroot/usr/share/casaos/shell/. "$H/shell/" 2>/dev/null || true
  # sources du catalogue d'apps : officielle, communautaires vérifiées, et « Danke IA » servie par le Gateway
  local store
  for store in \
    "https://cdn.jsdelivr.net/gh/IceWhaleTech/CasaOS-AppStore@gh-pages/store/main.zip" \
    "https://casaos-appstore.paodayag.dev/linuxserver.zip" \
    "https://casaos-appstore.paodayag.dev/coolstore.zip" \
    "https://github.com/mr-manuel/CasaOS-HomeAutomation-AppStore/archive/refs/tags/latest.zip" \
    "http://127.0.0.1:$PORT/danke-ia.zip"; do
    grep -qiF "appstore=$store" "$H/etc/app-management.conf" || \
      sed -i "/^\[server\]/a appstore=$store" "$H/etc/app-management.conf"
  done
  if [ -d "$ROOT/dist/www" ]; then  # l'interface compilée
    rm -rf "$H/www.new" && cp -r "$ROOT/dist/www" "$H/www.new" && rm -rf "$H/www" && mv "$H/www.new" "$H/www"
  fi
  [ -f "$ROOT/dist/danke-ia.zip" ] && cp "$ROOT/dist/danke-ia.zip" "$H/www/danke-ia.zip"
}

alive() { local f="$H/run/pids/$1.pid"; [ -s "$f" ] && kill -0 "$(cat "$f")" 2>/dev/null; }

launch() { # launch <nom> <commande…>
  local name="$1"; shift
  if alive "$name"; then return 0; fi
  # chaque service tourne sous un petit gardien, chef de son groupe et détaché du terminal :
  # il note son pid et relance le service s'il tombe (5 essais au plus par minute)
  ( cd "$H/etc" && PIDFILE="$H/run/pids/$name.pid" exec setsid nohup bash -c '
      echo $$ > "$PIDFILE"
      stop=0 child=0 n=0
      trap "stop=1; kill -TERM \$child 2>/dev/null" TERM INT
      while [ $stop = 0 ]; do
        start=$SECONDS
        "$@" & child=$!
        wait $child; code=$?
        [ $stop = 1 ] && { wait $child 2>/dev/null; break; }
        [ $((SECONDS - start)) -gt 60 ] && n=0
        n=$((n + 1))
        [ $n -gt 5 ] && { echo "$(date +%T) trop de redémarrages, abandon (code $code)"; exit 1; }
        echo "$(date +%T) service arrêté (code $code), redémarrage dans 2 s"
        sleep 2
      done' _ "$@" ) \
    >> "$H/log/$name.out" 2>&1 < /dev/null &
  local n=0; until [ -s "$H/run/pids/$name.pid" ] || [ $n -ge 25 ]; do n=$((n+1)); sleep 0.1; done
}

wait_file() { # wait_file <fichier> [secondes]
  local n=0 max=$(( ${2:-20} * 5 ))
  until [ -s "$1" ]; do n=$((n+1)); [ $n -ge $max ] && return 1; sleep 0.2; done
}

start() {
  prepare
  for b in casaos-gateway casaos-message-bus casaos-user-service casaos-app-management casaos; do
    [ -x "$BIN/$b" ] || { echo "binaire manquant : $BIN/$b (lance scripts/build-all.sh)"; exit 1; }
  done
  launch gateway "$BIN/casaos-gateway" -w "$H/www"
  wait_file "$H/run/management.url" 20 || { echo "le Gateway ne démarre pas : voir $H/log/gateway.out"; exit 1; }
  launch message-bus "$BIN/casaos-message-bus" -c "$H/etc/message-bus.conf"
  wait_file "$H/run/message-bus.url" 20 || echo "message-bus lent à démarrer"
  launch user-service "$BIN/casaos-user-service" -c "$H/etc/user-service.conf" -db "$H/db"
  [ -x "$BIN/casaos-local-storage" ] && launch local-storage "$BIN/casaos-local-storage" -c "$H/etc/local-storage.conf" -db "$H/db"
  launch app-management "$BIN/casaos-app-management" -c "$H/etc/app-management.conf"
  launch casaos "$BIN/casaos" -c "$H/etc/casaos.conf" -db "$H"
  if [ -x "$BIN/danke-hermes" ]; then launch danke-hermes "$BIN/danke-hermes" serve
  else echo "module Hermes absent : lance scripts/build-all.sh"; fi
  sleep 1
  status
  echo "Danke OS Agent : http://localhost:$PORT"
}

stop() {
  local i name pid
  for (( i=${#SERVICES[@]}-1; i>=0; i-- )); do
    name="${SERVICES[$i]}"
    if alive "$name"; then
      pid="$(cat "$H/run/pids/$name.pid")"
      kill -TERM "$pid" 2>/dev/null          # le gardien arrête son service puis se termine
    fi
  done
  local n=0
  while [ $n -lt 20 ]; do
    local left=0
    for name in "${SERVICES[@]}"; do alive "$name" && left=1; done
    [ $left = 0 ] && break
    n=$((n + 1)); sleep 0.25
  done
  for name in "${SERVICES[@]}"; do
    if [ -s "$H/run/pids/$name.pid" ]; then
      pid="$(cat "$H/run/pids/$name.pid")"
      kill -KILL -- "-$pid" 2>/dev/null       # dernier recours : tout le groupe (gardien et service)
    fi
    rm -f "$H/run/pids/$name.pid"
  done
  rm -f "$H"/run/*.url "$H"/run/*.pid
  echo "Danke OS Agent arrêté."
}

status() {
  local name
  for name in "${SERVICES[@]}"; do
    if alive "$name"; then printf '  %-16s en marche (pid %s)\n' "$name" "$(cat "$H/run/pids/$name.pid")"
    else printf '  %-16s arrêté\n' "$name"; fi
  done
}

case "${1:-start}" in
  start) start ;;
  stop) stop ;;
  restart) stop; start ;;
  status) status ;;
  logs) tail -n "${3:-60}" "$H/log/${2:-casaos}.out" ;;
  open)
    alive gateway || start
    for b in chromium google-chrome-stable brave; do
      command -v "$b" >/dev/null && exec setsid "$b" --app="http://localhost:$PORT" --class=danke-os >/dev/null 2>&1
    done
    exec xdg-open "http://localhost:$PORT" ;;
  *) echo "usage : danke-os start|stop|restart|status|logs [service]|open"; exit 2 ;;
esac
