#!/usr/bin/env bash
# Shared internal HTTPS/URL helpers for Sysadmin Chronicles launch and VM build scripts.
# Source this file; do not execute directly.

sc_internal_port() {
    printf '%s\n' "${PORT:-3000}"
}

sc_cert_dir() {
    printf '%s\n' "${SC_CERT_DIR:-$HOME/.local/share/sysadmin-chronicles/certs}"
}

sc_tls_cert() {
    printf '%s/server.crt\n' "$(sc_cert_dir)"
}

sc_tls_key() {
    printf '%s/server.key\n' "$(sc_cert_dir)"
}

sc_ca_cert() {
    printf '%s/ca.crt\n' "$(sc_cert_dir)"
}

sc_hud_url() {
    printf '%s\n' "${SC_HUD_URL:-https://portal.axiomworks.internal:$(sc_internal_port)}"
}

sc_sage_url() {
    printf '%s\n' "${SC_SAGE_URL:-https://sage.axiomworks.internal:$(sc_internal_port)/sage/}"
}

sc_company_url() {
    printf '%s\n' "${SC_COMPANY_URL:-https://www.axiomworks.corp/}"
}

sc_have_internal_certs() {
    [[ -f "$(sc_tls_cert)" && -f "$(sc_tls_key)" && -f "$(sc_ca_cert)" ]]
}

sc_ensure_internal_certs() {
    local project_root="$1"
    if sc_have_internal_certs; then
        return 0
    fi
    bash "$project_root/tools/setup/generate-certs.sh"
}

sc_export_internal_https_env() {
    export SC_CERT_DIR="$(sc_cert_dir)"
    export SC_TLS_CERT="$(sc_tls_cert)"
    export SC_TLS_KEY="$(sc_tls_key)"
    export SC_HUD_URL="$(sc_hud_url)"
    export SC_SAGE_URL="$(sc_sage_url)"
    export SC_COMPANY_URL="$(sc_company_url)"
}

sc_listen_pids() {
    local port="$1"
    if command -v lsof >/dev/null 2>&1; then
        lsof -tiTCP:"$port" -sTCP:LISTEN 2>/dev/null | sort -u
        return 0
    fi
    ss -H -ltnp "sport = :$port" 2>/dev/null \
        | sed -n 's/.*pid=\([0-9][0-9]*\).*/\1/p' \
        | sort -u
}

sc_pid_is_repo_server() {
    local pid="$1"
    local project_root="$2"
    local server_dir="$project_root/server"
    local cwd=""
    local cmdline=""

    [[ -r "/proc/$pid/cmdline" ]] || return 1
    cwd="$(readlink -f "/proc/$pid/cwd" 2>/dev/null || true)"
    cmdline="$(tr '\0' ' ' < "/proc/$pid/cmdline" 2>/dev/null || true)"

    [[ "$cwd" == "$server_dir" ]] || return 1
    [[ "$cmdline" == *"node"* && "$cmdline" == *"src/index.js"* ]]
}

sc_pid_has_internal_tls() {
    local pid="$1"
    [[ -r "/proc/$pid/environ" ]] || return 1
    tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null \
        | grep -q '^SC_TLS_CERT=.*server\.crt$' \
        && tr '\0' '\n' < "/proc/$pid/environ" 2>/dev/null \
        | grep -q '^SC_TLS_KEY=.*server\.key$'
}

sc_stop_pid() {
    local pid="$1"
    kill "$pid" 2>/dev/null || true
    for _ in 1 2 3 4 5 6 7 8 9 10; do
        kill -0 "$pid" 2>/dev/null || return 0
        sleep 0.2
    done
    kill -TERM "$pid" 2>/dev/null || true
}
