#!/usr/bin/env bash
# fix-terminal-server-deps.sh
#
# Rebuilds the WHP terminal-server's node_modules and restarts the service.
#
# Why: the terminal-server service typically runs for weeks or months
# between restarts. If a dependency's files are lost (filesystem cleanup,
# partial npm update, package-lock drift) the live process keeps serving
# old cached modules until the missing file is actually touched — commonly
# inside authenticate() when someone tries the terminal after a long idle
# period. Symptom on the client: "Authentication failed" every time;
# server log shows:
#     Error: Cannot find module '../encodings'
#       at .../node_modules/mysql2/node_modules/iconv-lite/lib/index.js
#
# Safe to run multiple times.
set -euo pipefail

SERVICE=whp-terminal
DEP_DIR=/root/whp/terminal-server

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*"; }

if [[ ! -d "${DEP_DIR}" ]]; then
    log "FATAL: ${DEP_DIR} not found. Is WHP installed on this host?"
    exit 1
fi

if [[ ! -f "${DEP_DIR}/package.json" ]]; then
    log "FATAL: ${DEP_DIR}/package.json missing — cannot reinstall."
    exit 1
fi

log "Stopping ${SERVICE}..."
systemctl stop "${SERVICE}" || log "  (service was not running — continuing)"

log "Wiping ${DEP_DIR}/node_modules and package-lock.json..."
rm -rf "${DEP_DIR}/node_modules" "${DEP_DIR}/package-lock.json"

log "Running npm install --omit=dev in ${DEP_DIR}..."
cd "${DEP_DIR}"
if ! npm install --omit=dev; then
    log "FATAL: npm install failed — service left stopped for inspection."
    exit 1
fi

log "Starting ${SERVICE}..."
systemctl start "${SERVICE}"
sleep 2

# Verify the service came back up.
if ! systemctl is-active --quiet "${SERVICE}"; then
    log "FATAL: ${SERVICE} did not start — check 'journalctl -u ${SERVICE} -n 50'."
    exit 1
fi

# Verify the iconv-lite encodings dir is present (most common missing piece).
ENC_DIR="${DEP_DIR}/node_modules/mysql2/node_modules/iconv-lite/encodings"
if [[ -d "${ENC_DIR}" ]]; then
    log "OK: ${ENC_DIR} present."
else
    log "WARNING: ${ENC_DIR} NOT present after install. mysql2 module layout may have changed."
fi

log "fix-terminal-server-deps.sh: OK"
