#!/usr/bin/env bash
#
# NACEF SIC connector — one-command manager.
#
#   ./nacef-connector.sh install     # install as a service, start on boot
#   ./nacef-connector.sh status      # is it running? can it reach the SIC?
#   ./nacef-connector.sh restart
#   ./nacef-connector.sh uninstall
#   ./nacef-connector.sh run         # run in this terminal (no install, Ctrl-C to stop)
#
# The connector lets a cloud page (<tenant>.kaissflow.com) call the local NACEF
# SIC. It runs on the cashier's machine, next to the SIC/SMDF.
#
set -euo pipefail

SERVICE=nacef-sic-connector
INSTALL_DIR="${INSTALL_DIR:-/opt/nacef-connector}"
SRC="$(cd "$(dirname "$0")" && pwd)/nacef_sic_connector.py"

# --- tunables (override with env before the command) ----------------------
LISTEN_HOST="${LISTEN_HOST:-127.0.0.1}"
LISTEN_PORT="${LISTEN_PORT:-10016}"
TARGET_HOST="${TARGET_HOST:-127.0.0.1}"
TARGET_PORT="${TARGET_PORT:-10006}"
ALLOW_SUFFIXES="${ALLOW_SUFFIXES:-.kaissflow.com,localhost,127.0.0.1}"

c_green(){ printf '\033[0;32m%s\033[0m\n' "$1"; }
c_red(){   printf '\033[0;31m%s\033[0m\n' "$1"; }
c_dim(){   printf '\033[2m%s\033[0m\n' "$1"; }

need_root(){ [ "$(id -u)" -eq 0 ] || { c_red "Run with sudo:  sudo $0 $1"; exit 1; }; }
need_py(){ command -v python3 >/dev/null || { c_red "python3 is required."; exit 1; }; }

test_connectivity(){
  # Two distinct questions, asked separately. The old version ran one proxied
  # request with a 5s timeout and reported every failure as "connector not
  # answering" — but that request goes THROUGH to the SIC, so a hung SIC was
  # indistinguishable from a dead connector, and pointed at the wrong fix.
  local base="http://${LISTEN_HOST}:${LISTEN_PORT}"

  # 1) is anything listening?
  if ! timeout 2 bash -c "cat < /dev/null > /dev/tcp/${LISTEN_HOST}/${LISTEN_PORT}" 2>/dev/null; then
    c_red "  ✗ connector is DOWN: nothing listening on ${base}"
    c_dim "     -> sudo $0 restart   (check ${NACEF_LOG:-/tmp/nacef-connector.log})"
    return
  fi

  # 2) can it reach the SIC? Generous timeout: the SIC may talk to NACEF.
  local code
  code=$(curl -s -m 30 -o /dev/null -w '%{http_code}' \
         -H "Origin: https://test.kaissflow.com" \
         "${base}/sic/external/manifest" 2>/dev/null || echo 000)
  case "$code" in
    200) c_green "  ✓ connector up, SIC reachable and PAIRED (HTTP 200)";;
    401) c_green "  ✓ connector up, SIC reachable (HTTP 401 = not paired yet)";;
    000) c_red   "  ✗ connector up, but the SIC on ${TARGET_HOST}:${TARGET_PORT} did NOT answer in 30s"
         c_dim   "     -> the SIC/S-MDF is hung or very slow; restart the NACEF SIC Agent";;
    50*) c_red   "  ✗ connector up, but the SIC on ${TARGET_HOST}:${TARGET_PORT} is unreachable (HTTP $code)"
         c_dim   "     -> is the NACEF SIC Agent service running?";;
    *)   c_dim   "  • connector up, SIC replied HTTP $code";;
  esac
}

cmd_install(){
  need_root install; need_py
  [ -f "$SRC" ] || { c_red "Missing $SRC"; exit 1; }
  install -d "$INSTALL_DIR"
  install -m 0644 "$SRC" "$INSTALL_DIR/nacef_sic_connector.py"
  cat > "/etc/systemd/system/${SERVICE}.service" <<EOF
[Unit]
Description=NACEF SIC browser connector (CORS/PNA -> ${TARGET_HOST}:${TARGET_PORT})
After=network-online.target smdf.service
Wants=network-online.target

[Service]
Type=simple
Environment=LISTEN_HOST=${LISTEN_HOST}
Environment=LISTEN_PORT=${LISTEN_PORT}
Environment=TARGET_HOST=${TARGET_HOST}
Environment=TARGET_PORT=${TARGET_PORT}
Environment=ALLOW_SUFFIXES=${ALLOW_SUFFIXES}
ExecStart=/usr/bin/env python3 ${INSTALL_DIR}/nacef_sic_connector.py
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target
EOF
  systemctl daemon-reload
  systemctl enable "$SERVICE"
  # restart, not "enable --now": on an upgrade the unit is already active and
  # --now is a no-op, leaving the old process running with the old
  # ALLOW_SUFFIXES. That silently keeps a stale origin allow-list in place.
  systemctl restart "$SERVICE"
  sleep 1
  c_green "Installed and started: ${SERVICE}"
  c_dim   "  listen  http://${LISTEN_HOST}:${LISTEN_PORT}"
  c_dim   "  -> SIC  http://${TARGET_HOST}:${TARGET_PORT}"
  c_dim   "  origins ${ALLOW_SUFFIXES}"
  test_connectivity
}

cmd_status(){
  if systemctl list-unit-files 2>/dev/null | grep -q "^${SERVICE}.service"; then
    systemctl is-active --quiet "$SERVICE" && c_green "service: active (enabled=$(systemctl is-enabled "$SERVICE" 2>/dev/null))" \
      || c_red "service: NOT running  (sudo $0 restart)"
  else
    c_dim "service not installed (using foreground 'run'? that's fine)"
  fi
  test_connectivity
}

cmd_restart(){ need_root restart; systemctl restart "$SERVICE"; sleep 1; cmd_status; }

cmd_uninstall(){
  need_root uninstall
  systemctl disable --now "$SERVICE" 2>/dev/null || true
  rm -f "/etc/systemd/system/${SERVICE}.service"
  systemctl daemon-reload
  rm -rf "$INSTALL_DIR"
  c_green "Uninstalled ${SERVICE}"
}

cmd_run(){
  need_py
  c_dim "Running in foreground (Ctrl-C to stop). For permanent use: sudo $0 install"
  LISTEN_HOST="$LISTEN_HOST" LISTEN_PORT="$LISTEN_PORT" \
  TARGET_HOST="$TARGET_HOST" TARGET_PORT="$TARGET_PORT" \
  ALLOW_SUFFIXES="$ALLOW_SUFFIXES" exec python3 "$SRC"
}

case "${1:-}" in
  install)   cmd_install;;
  status)    cmd_status;;
  restart)   cmd_restart;;
  uninstall) cmd_uninstall;;
  run)       cmd_run;;
  *) echo "usage: $0 {install|status|restart|uninstall|run}"; exit 2;;
esac
