#!/usr/bin/env bash
# dms-ui installer. Idempotent. Re-running is safe.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
VENV_PY="/home/hermes/venv/bin/python"
SERVICE_SRC="$HERE/systemd/dms-ui.service"
SERVICE_DST="/etc/systemd/system/dms-ui.service"
CONFIG_DST="/home/hermes/dms-ui/config.json"
ASKPASS="/home/hermes/.ssh-askpass.sh"

log() { printf '\033[1;36m[dms-ui install]\033[0m %s\n' "$*"; }
warn() { printf '\033[1;33m[dms-ui install]\033[0m %s\n' "$*" >&2; }
die() { printf '\033[1;31m[dms-ui install]\033[0m %s\n' "$*" >&2; exit 1; }

# 1. preflight ----------------------------------------------------------------
[[ -x "$VENV_PY" ]] || die "shared venv missing at /home/hermes/venv (need $VENV_PY)"
[[ -f "$ASKPASS" ]] || warn "askpass script $ASKPASS not present; SSH password commands will fail"

# 2. ensure paramiko in the shared venv ---------------------------------------
if ! "$VENV_PY" -c "import paramiko" >/dev/null 2>&1; then
  log "pip install paramiko into /home/hermes/venv"
  /home/hermes/venv/bin/pip install --quiet paramiko
else
  log "paramiko already installed"
fi

# 3. seed config.json (only if absent) ----------------------------------------
if [[ ! -f "$CONFIG_DST" ]]; then
  log "seeding $CONFIG_DST from config.example.json"
  cp "$HERE/config.example.json" "$CONFIG_DST"
  chmod 600 "$CONFIG_DST" || true
else
  log "$CONFIG_DST already exists; leaving alone"
fi

# 4. install systemd unit -----------------------------------------------------
if [[ -w /etc/systemd/system ]] || [[ $EUID -eq 0 ]]; then
  if [[ ! -f "$SERVICE_DST" ]] || ! cmp -s "$SERVICE_SRC" "$SERVICE_DST"; then
    log "installing $SERVICE_DST"
    cp "$SERVICE_SRC" "$SERVICE_DST"
    systemctl daemon-reload
  else
    log "systemd unit unchanged"
  fi
  if ! systemctl is-enabled --quiet dms-ui 2>/dev/null; then
    log "enabling dms-ui"
    systemctl enable dms-ui
  fi
  if ! systemctl is-active --quiet dms-ui 2>/dev/null; then
    log "starting dms-ui"
    systemctl restart dms-ui || systemctl start dms-ui
  else
    log "dms-ui already running; restarting to pick up changes"
    systemctl restart dms-ui
  fi
else
  warn "no write access to /etc/systemd/system; install the unit manually:"
  warn "  sudo cp $SERVICE_SRC $SERVICE_DST && sudo systemctl daemon-reload"
  warn "  sudo systemctl enable --now dms-ui"
fi

log "done. Web UI: http://127.0.0.1:8792  (default password: admin)"
