#!/bin/bash
# ============================================================================
# SoftSwitch Platform & System Distribution Subsystem
#
# File: ring2all-system-updater
# Author: SoftSwitch Team
#
# Description:
# Least-privilege root helper executed via zero-wildcard sudoers to refresh APT
# metadata and spawn a detached transient systemd unit (`ring2all-updater`) in
# PID 1's root mount namespace and independent cgroup. Safely survives API
# daemon restarts (`DEBIAN/postinst`) and operates outside `ProtectSystem=strict`.
# ============================================================================

set -uo pipefail

STATE_DIR="/var/log/SoftSwitch"
REQ_FILE="${STATE_DIR}/system-update-request.json"
STATUS_FILE="${STATE_DIR}/system-update-status.json"
LOG_FILE="${STATE_DIR}/system-update.log"
LOCK_FILE="/run/lock/ring2all-updater.lock"
UNIT_NAME="ring2all-updater"

mkdir -p "${STATE_DIR}"
chmod 775 "${STATE_DIR}" 2>/dev/null || true
if getent group softswitch >/dev/null 2>&1; then
  chown root:softswitch "${STATE_DIR}" 2>/dev/null || true
fi

strip_ansi() {
  sed -r 's/\x1B\[[0-9;]*[a-zA-Z]//g'
}

log_line() {
  local tag="$1"
  shift
  local msg="$*"
  printf '[%s] %s %s\n' "${tag}" "$(date '+%H:%M:%S')" "${msg}" >> "${LOG_FILE}"
  chmod 644 "${LOG_FILE}" 2>/dev/null || true
}

write_status() {
  local status="$1"
  local phase="$2"
  local progress="$3"
  local stage_msg="$4"
  local err_msg="${5:-}"
  local checks_json="${6:-[]}"

  python3 - "$STATUS_FILE" "$JOB_ID" "$status" "$phase" "$progress" "$stage_msg" "$STARTED_AT" "$TARGET_VERSION" "$err_msg" "$checks_json" <<'PYEOF'
import json, os, sys, datetime

(
    status_path,
    job_id,
    status,
    phase,
    progress,
    stage_msg,
    started_at,
    target_ver,
    err_msg,
    checks_raw,
) = sys.argv[1:11]

try:
    checks = json.loads(checks_raw)
except Exception:
    checks = []

payload = {
    "jobId": job_id,
    "status": status,
    "phase": phase,
    "progress": int(progress),
    "stageMessage": stage_msg,
    "startedAt": started_at,
    "completedAt": datetime.datetime.now(datetime.timezone.utc).isoformat() if status in ("completed", "failed") else None,
    "targetVersion": target_ver or None,
    "error": err_msg or None,
    "postflightChecks": checks,
}

tmp_path = status_path + ".tmp"
with open(tmp_path, "w", encoding="utf-8") as fh:
    json.dump(payload, fh)
os.chmod(tmp_path, 0o644)
os.replace(tmp_path, status_path)
PYEOF
}

validate_and_load_request() {
  if [ ! -f "${REQ_FILE}" ] || [ -L "${REQ_FILE}" ]; then
    echo "Missing or invalid update request file: ${REQ_FILE}" >&2
    exit 1
  fi

  local parsed
  if ! parsed=$(python3 - "${REQ_FILE}" <<'PYEOF'
import json, re, sys

req_path = sys.argv[1]
with open(req_path, "r", encoding="utf-8") as fh:
    data = json.load(fh)

job_id = str(data.get("jobId", "")).strip()
app = str(data.get("app", "")).strip()
action = str(data.get("action", "upgrade") or "upgrade").strip().lower()
target_ver = str(data.get("targetVersion", "") or "").strip()
started_at = str(data.get("startedAt", "") or "").strip()
pre_backup = "1" if bool(data.get("preBackup", True)) else "0"
graceful_drain = "1" if bool(data.get("gracefulDrain", False)) else "0"
packages = data.get("packages", [])

CORE_PROTECTED_PACKAGES = {
    "softswitch-all",
    "softswitch-pbx-all",
    "softswitch-pbx-core",
    "softswitch-pbx-db",
    "softswitch-pbx-api",
    "softswitch-pbx-monitoring-api",
    "softswitch-pbx-admin",
    "softswitch-pbx-telephony",
}

if not re.match(r"^[a-zA-Z0-9_-]{6,64}$", job_id):
    raise SystemExit("Invalid jobId format")
if app not in ("pbx", "sbc", "bss", "dms", "nms", "ncx", "video", "starter"):
    raise SystemExit("Invalid app identifier")
if action not in ("upgrade", "install", "remove"):
    raise SystemExit("Invalid action identifier")
if target_ver and not re.match(r"^[a-zA-Z0-9.+:~_-]{1,48}$", target_ver):
    target_ver = ""
if not isinstance(packages, list) or len(packages) == 0 or len(packages) > 40:
    raise SystemExit("Invalid packages list")

clean_pkgs = []
for pkg in packages:
    p = str(pkg).strip()
    if not re.match(r"^softswitch-[a-z0-9-]+$", p):
        raise SystemExit(f"Forbidden package name: {p}")
    if action == "remove" and p in CORE_PROTECTED_PACKAGES:
        raise SystemExit(f"Core immutable package cannot be removed: {p}")
    clean_pkgs.append(p)

print(job_id)
print(app)
print(action)
print(target_ver)
print(started_at)
print(pre_backup)
print(graceful_drain)
print(" ".join(clean_pkgs))
PYEOF
  ); then
    echo "Update request validation failed." >&2
    exit 1
  fi

  JOB_ID=$(printf '%s\n' "${parsed}" | sed -n '1p')
  APP_KEY=$(printf '%s\n' "${parsed}" | sed -n '2p')
  ACTION_KIND=$(printf '%s\n' "${parsed}" | sed -n '3p')
  TARGET_VERSION=$(printf '%s\n' "${parsed}" | sed -n '4p')
  STARTED_AT=$(printf '%s\n' "${parsed}" | sed -n '5p')
  PRE_BACKUP=$(printf '%s\n' "${parsed}" | sed -n '6p')
  GRACEFUL_DRAIN=$(printf '%s\n' "${parsed}" | sed -n '7p')
  PACKAGES_STR=$(printf '%s\n' "${parsed}" | sed -n '8p')
  [ -z "${STARTED_AT}" ] && STARTED_AT="$(date -u '+%Y-%m-%dT%H:%M:%SZ')"
}

SELF_SCRIPT="$(readlink -f "$0" 2>/dev/null || echo "/usr/local/libexec/ring2all-system-updater")"

cmd="${1:-}"

case "${cmd}" in
  refresh)
    if systemctl is-active --quiet "${UNIT_NAME}.service" 2>/dev/null; then
      echo "Updater unit is currently active; skipping concurrent refresh."
      exit 0
    fi
    export DEBIAN_FRONTEND=noninteractive
    timeout 45 apt-get update -q
    exit $?
    ;;

  launch)
    if systemctl is-active --quiet "${UNIT_NAME}.service" 2>/dev/null; then
      echo "System update service is already running." >&2
      exit 2
    fi

    validate_and_load_request

    : > "${LOG_FILE}"
    chmod 644 "${LOG_FILE}" 2>/dev/null || true
    log_line "SYSTEMD" "Spawning detached systemd unit (${UNIT_NAME}.service) [${ACTION_KIND}] for packages: ${PACKAGES_STR}"
    write_status "running" "initializing" 6 "Launching detached systemd package manager (${ACTION_KIND})..."

    systemctl reset-failed "${UNIT_NAME}.service" 2>/dev/null || true
    /usr/bin/systemd-run \
      --unit="${UNIT_NAME}" \
      --collect \
      --description="Ring2All Detached System Package Manager" \
      "${SELF_SCRIPT}" run-worker
    exit $?
    ;;

  run-worker)
    validate_and_load_request

    exec 9>"${LOCK_FILE}"
    if ! flock -n 9; then
      log_line "ERROR" "Unable to acquire updater lock (${LOCK_FILE}); another operation is active."
      write_status "failed" "failed" 0 "Updater lock busy" "Another package operation holds ${LOCK_FILE}."
      exit 1
    fi

    export DEBIAN_FRONTEND=noninteractive
    read -r -a PKG_ARRAY <<< "${PACKAGES_STR}"

    # Phase 1: Optional Pre-Operation Backup Snapshot
    if [ "${PRE_BACKUP}" = "1" ]; then
      write_status "running" "backup" 14 "Creating pre-operation configuration and database snapshot..."
      log_line "BACKUP" "Starting pre-operation safety snapshot..."
      BACKUP_DIR="/var/backups/softswitch"
      mkdir -p "${BACKUP_DIR}"
      SNAP_PATH="${BACKUP_DIR}/pre-update-${APP_KEY}-${JOB_ID}.tar.gz"

      if [ -d "/etc/softswitch" ]; then
        tar -czf "${SNAP_PATH}" /etc/softswitch 2>/dev/null || true
        log_line "BACKUP" "Saved /etc/softswitch configuration archive to ${SNAP_PATH}"
      fi

      if command -v pg_dump >/dev/null 2>&1 && systemctl is-active --quiet postgresql 2>/dev/null; then
        case "${APP_KEY}" in
          pbx) DB_LIST="ss_admin ss_telephony" ;;
          sbc) DB_LIST="sbc_admin kamailio" ;;
          bss) DB_LIST="ss_billing" ;;
          dms) DB_LIST="ss_dms" ;;
          nms) DB_LIST="ss_nms" ;;
          ncx) DB_LIST="ss_admin ss_telephony" ;;
          *)   DB_LIST="" ;;
        esac
        for db_name in ${DB_LIST}; do
          if sudo -u postgres psql -lqt 2>/dev/null | cut -d \| -f 1 | grep -qw "${db_name}"; then
            sudo -u postgres pg_dump "${db_name}" 2>/dev/null | gzip > "${BACKUP_DIR}/pre-update-${db_name}-${JOB_ID}.sql.gz" || true
            log_line "BACKUP" "Database ${db_name} dumped cleanly."
          fi
        done
      fi
    else
      log_line "BACKUP" "Pre-operation snapshot skipped by administrator preference."
    fi

    # Optional Graceful Call Drain for PBX
    if [ "${GRACEFUL_DRAIN}" = "1" ] && [ "${APP_KEY}" = "pbx" ] && command -v fs_cli >/dev/null 2>&1; then
      write_status "running" "backup" 22 "Waiting briefly for active SIP calls to drain..."
      for _ in $(seq 1 15); do
        ACTIVE_CALLS=$(fs_cli -x "show calls count" 2>/dev/null | awk '/total/ {print $1}' | head -n 1)
        if [ -z "${ACTIVE_CALLS}" ] || [ "${ACTIVE_CALLS}" = "0" ]; then
          break
        fi
        log_line "WARN" "${ACTIVE_CALLS} active SIP call(s) remaining; waiting 2s..."
        sleep 2
      done
    fi

    if [ "${ACTION_KIND}" = "remove" ]; then
      # Filter target list to packages actually installed on the host so remove never fails on optional subpackages
      INSTALLED_TARGETS=()
      for pkg_item in "${PKG_ARRAY[@]}"; do
        PKG_STATE=$(dpkg-query -W -f='${Status}' "${pkg_item}" 2>/dev/null || true)
        if printf '%s' "${PKG_STATE}" | grep -q "install ok installed"; then
          INSTALLED_TARGETS+=("${pkg_item}")
        fi
      done

      write_status "running" "downloading" 40 "Preparing safe package removal (preserving databases & configs)..."
      if [ "${#INSTALLED_TARGETS[@]}" -eq 0 ]; then
        log_line "WARN" "None of the target packages are currently installed; nothing to remove."
      else
        log_line "DPKG" "Removing packages (non-purge): ${INSTALLED_TARGETS[*]}"
        write_status "running" "installing" 68 "Uninstalling packages and reloading services..."
        set -o pipefail
        apt-get remove -y "${INSTALLED_TARGETS[@]}" 2>&1 | strip_ansi | while IFS= read -r line; do
          [ -z "${line}" ] && continue
          if printf '%s' "${line}" | grep -qiE 'systemctl|Removing|reload|nginx'; then
            write_status "running" "restarting" 84 "Stopping removed services and reloading HTTP proxy..."
            log_line "RESTART" "${line}"
          else
            log_line "DPKG" "${line}"
          fi
        done
        APT_EXIT=$?
        if [ "${APT_EXIT}" -ne 0 ]; then
          log_line "ERROR" "apt-get remove exited with code ${APT_EXIT}."
          write_status "failed" "failed" 80 "Package removal failed" "apt-get remove exited with status code ${APT_EXIT}."
          exit "${APT_EXIT}"
        fi
      fi

      # Ensure shared updater remains intact if softswitch-ncx-api removal deleted /usr/local/libexec/ring2all-system-updater
      if [ ! -f "/usr/local/libexec/ring2all-system-updater" ] && [ -f "/usr/share/softswitch-pbx-api/ring2all-system-updater" ]; then
        install -o root -g root -m 0755 /usr/share/softswitch-pbx-api/ring2all-system-updater /usr/local/libexec/ring2all-system-updater 2>/dev/null || true
      fi

      if command -v nginx >/dev/null 2>&1 && nginx -t >/dev/null 2>&1; then
        systemctl reload nginx 2>/dev/null || true
      fi
    else
      # Phase 2: APT Metadata Refresh & Package Download
      write_status "running" "downloading" 35 "Refreshing signed APT repository and downloading packages..."
      log_line "APT" "Refreshing package lists from configured APT sources..."
      if ! apt-get update -q 2>&1 | strip_ansi | while IFS= read -r line; do
        [ -n "${line}" ] && log_line "APT" "${line}"
      done; then
        log_line "ERROR" "Failed to refresh APT repository metadata."
        write_status "failed" "failed" 35 "APT repository update failed" "apt-get update failed; check network and repository configuration."
        exit 1
      fi

      APT_INSTALL_FLAGS=()
      if [ "${ACTION_KIND}" = "upgrade" ]; then
        APT_INSTALL_FLAGS+=(--only-upgrade)
      fi

      write_status "running" "downloading" 48 "Downloading verified .deb archives..."
      if ! apt-get install --download-only -y "${APT_INSTALL_FLAGS[@]}" "${PKG_ARRAY[@]}" 2>&1 | strip_ansi | while IFS= read -r line; do
        [ -n "${line}" ] && log_line "APT" "${line}"
      done; then
        log_line "ERROR" "Failed to download target packages: ${PACKAGES_STR}"
        write_status "failed" "failed" 48 "Package download failed" "Unable to download target packages from APT repository."
        exit 1
      fi

      # Phase 3 & 4: Unpack, Schema Migrations & Service Restarts
      write_status "running" "installing" 68 "Unpacking packages, running migrations, and restarting services..."
      log_line "DPKG" "Applying non-interactive ${ACTION_KIND} (--force-confdef --force-confold) for: ${PACKAGES_STR}"

      set -o pipefail
      apt-get install -y \
        -o Dpkg::Options::="--force-confdef" \
        -o Dpkg::Options::="--force-confold" \
        "${APT_INSTALL_FLAGS[@]}" "${PKG_ARRAY[@]}" 2>&1 | strip_ansi | while IFS= read -r line; do
          [ -z "${line}" ] && continue
          if printf '%s' "${line}" | grep -qiE 'systemctl restart|restarting|Setting up'; then
            write_status "running" "restarting" 84 "Configuring packages and restarting application services..."
            log_line "RESTART" "${line}"
          else
            log_line "DPKG" "${line}"
          fi
        done
      APT_EXIT=$?

      if [ "${APT_EXIT}" -ne 0 ]; then
        log_line "ERROR" "dpkg/apt-get exited with code ${APT_EXIT}."
        write_status "failed" "failed" 80 "Package installation failed" "apt-get install exited with status code ${APT_EXIT}."
        exit "${APT_EXIT}"
      fi
    fi

    # Canonical PBX web root & uploads permission sanitation (prevents Nginx 418/502 fallback)
    if { [ "${APP_KEY}" = "pbx" ] || [ "${APP_KEY}" = "ncx" ]; } && [ -d "/var/www/softswitch" ]; then
      chmod 755 /var/www /var/www/softswitch 2>/dev/null || true
      if [ -d "/var/www/softswitch/uploads" ]; then
        find /var/www/softswitch/uploads -type d -exec chmod 755 {} + 2>/dev/null || true
        find /var/www/softswitch/uploads -type f -exec chmod 644 {} + 2>/dev/null || true
      fi
      log_line "HEALTH" "Verified /var/www/softswitch and /uploads traversal permissions."
    fi

    # Phase 5: Post-Flight Service Health Verification
    write_status "running" "verifying" 94 "Verifying system services post-operation..."
    case "${APP_KEY}" in
      pbx)   SERVICES_CHECK="postgresql freeswitch softswitch-api nginx" ;;
      sbc)   SERVICES_CHECK="postgresql kamailio sbc-api nginx" ;;
      bss)   SERVICES_CHECK="postgresql softswitch-bss-api nginx" ;;
      dms)   SERVICES_CHECK="postgresql softswitch-dms-api nginx" ;;
      nms)   SERVICES_CHECK="postgresql softswitch-nms-api nginx" ;;
      ncx)   SERVICES_CHECK="postgresql softswitch-ncx-api softswitch-ncx-worker softswitch-ncx-stt softswitch-api nginx" ;;
      video) SERVICES_CHECK="redis-server softswitch-video-sfu softswitch-video-sip softswitch-video-egress softswitch-api" ;;
      *)     SERVICES_CHECK="postgresql nginx" ;;
    esac

    CHECKS_JSON=$(python3 - ${SERVICES_CHECK} <<'PYEOF'
import json, subprocess, sys

results = []
for svc in sys.argv[1:]:
    unit_check = subprocess.run(
        ["systemctl", "list-unit-files", f"{svc}.service"],
        capture_output=True, text=True
    )
    if svc not in unit_check.stdout:
        continue
    res = subprocess.run(["systemctl", "is-active", svc], capture_output=True, text=True)
    is_active = res.stdout.strip() == "active"
    results.append({"service": svc, "active": is_active, "detail": res.stdout.strip()})

print(json.dumps(results))
PYEOF
    )

    log_line "SUCCESS" "Package operation (${ACTION_KIND}) completed cleanly. Verified services: ${SERVICES_CHECK}"
    write_status "completed" "completed" 100 "Operation completed and verified." "" "${CHECKS_JSON}"
    rm -f "${REQ_FILE}" 2>/dev/null || true
    exit 0
    ;;

  *)
    echo "Usage: $0 {refresh|launch|run-worker}" >&2
    exit 1
    ;;
esac
