#!/usr/bin/env bash
#
# install-nacef-agent.sh — one download, one command for a shop.
#
# Installs, on the cashier's Linux machine, the three local pieces needed for
# the "cloud POS + local SMDF" model:
#
#   1. NACEF SMDF Server   (Ministry installer  SMDF.sh)  -> port 10004
#   2. NACEF SIC Agent     (Ministry installer  SIC.sh)   -> port 10006
#   3. CAMELSOFT connector (nacef_sic_connector.py)        -> port 10016
#      (lets the cloud POS page talk to the local SIC via CORS/PNA)
#
# Idempotent: anything already installed/running is left alone. Run it as a
# NORMAL user (it will ask for sudo when needed):
#
#   ./install-nacef-agent.sh
#
# Point it at the Ministry package folder if it isn't the default:
#   NACEF_PKG_DIR=~/Downloads/Gateway_SMDF_Linux ./install-nacef-agent.sh
#
set -euo pipefail

DIR="$(cd "$(dirname "$0")" && pwd)"
NACEF_PKG_DIR="${NACEF_PKG_DIR:-$HOME/Downloads/Gateway_SMDF_Linux}"
SMDF_INSTALLER="${SMDF_INSTALLER:-$NACEF_PKG_DIR/SMDF.sh}"
SIC_INSTALLER="${SIC_INSTALLER:-$NACEF_PKG_DIR/SIC.sh}"

# connector tunables (passed through to nacef-connector.sh)
export LISTEN_PORT="${LISTEN_PORT:-10016}"
export TARGET_PORT="${TARGET_PORT:-10006}"
export ALLOW_SUFFIXES="${ALLOW_SUFFIXES:-.kaissflow.com,localhost,127.0.0.1}"

g(){ printf '\033[0;32m%s\033[0m\n' "$1"; }
r(){ printf '\033[0;31m%s\033[0m\n' "$1"; }
b(){ printf '\033[1m%s\033[0m\n' "$1"; }
d(){ printf '\033[2m%s\033[0m\n' "$1"; }

as_root(){ if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi; }
listening(){ (ss -tln 2>/dev/null || netstat -tln 2>/dev/null) | grep -q ":$1 "; }

step(){ printf '\n'; b "==> $1"; }

# --- 1. SMDF Server -------------------------------------------------------- #
install_smdf(){
  step "1/3  NACEF SMDF Server (port 10004)"
  if [ -d /opt/smdf ] || systemctl is-active --quiet smdf 2>/dev/null || listening 10004; then
    g "  already installed / running — skipping"
    return
  fi
  if [ ! -f "$SMDF_INSTALLER" ]; then
    r "  SMDF installer not found: $SMDF_INSTALLER"
    d "  Download the Ministry package and set NACEF_PKG_DIR, then re-run."
    exit 1
  fi
  d "  running the Ministry SMDF installer (asks for sudo)…"
  ( cd "$(dirname "$SMDF_INSTALLER")" && sh "$(basename "$SMDF_INSTALLER")" )
  g "  SMDF installed"
}

# --- 2. SIC Agent ---------------------------------------------------------- #
install_sic(){
  step "2/3  NACEF SIC Agent (port 10006)"
  if [ -d /opt/sic ] || listening 10006; then
    g "  already installed / running — skipping"
    return
  fi
  if [ ! -f "$SIC_INSTALLER" ]; then
    r "  SIC installer not found: $SIC_INSTALLER"
    d "  Download the Ministry package and set NACEF_PKG_DIR, then re-run."
    exit 1
  fi
  d "  running the Ministry SIC installer (asks for sudo)…"
  ( cd "$(dirname "$SIC_INSTALLER")" && sh "$(basename "$SIC_INSTALLER")" )
  g "  SIC installed"
}

# --- 3. CAMELSOFT connector ------------------------------------------------ #
install_connector(){
  step "3/3  CAMELSOFT browser connector (port ${LISTEN_PORT})"
  as_root env LISTEN_PORT="$LISTEN_PORT" TARGET_PORT="$TARGET_PORT" \
    ALLOW_SUFFIXES="$ALLOW_SUFFIXES" "$DIR/nacef-connector.sh" install
}

# --- verify the whole chain ------------------------------------------------ #
verify(){
  step "Verification"
  listening 10004 && g "  ✓ SMDF listening on 10004" || r "  ✗ SMDF not listening on 10004"
  listening 10006 && g "  ✓ SIC  listening on 10006" || r "  ✗ SIC not listening on 10006 (needs a desktop session for the first run)"
  local code
  code=$(curl -s -m 5 -o /dev/null -w '%{http_code}' -H "Origin: https://test.kaissflow.com" \
         "http://127.0.0.1:${LISTEN_PORT}/sic/external/manifest" 2>/dev/null || echo 000)
  case "$code" in
    200) g "  ✓ connector -> SIC OK, device PAIRED (HTTP 200)";;
    401) g "  ✓ connector -> SIC OK (HTTP 401 = reachable, not paired yet)";;
    000) r "  ✗ connector not answering on ${LISTEN_PORT}";;
    *)   d "  • connector -> SIC replied HTTP $code";;
  esac
}

next_steps(){
  step "Next steps"
  cat <<EOF
  1. Declare the equipment (its MAC) on homologation.nacef.tn and get your
     IMDF + pairing code. Make sure the machine's fixed IP matches the declared,
     validated IP.
  2. PAIRING must be done from the machine's DESKTOP SESSION (the SIC shows
     windows). In your cloud POS click "Request certificate", fill the SIC
     windows (pairing+IMDF, OTP, PIN), then go to the registration unit, then
     "Synchronize".
  3. In the cloud POS, set the S-MDF Agent URL to this machine's connector,
     e.g.  http://127.0.0.1:${LISTEN_PORT}
  Check anytime with:  $DIR/nacef-connector.sh status
EOF
}

b "CAMELSOFT — NACEF local agent installer"
install_smdf
install_sic
install_connector
verify
next_steps
g "\nDone."
