#!/bin/bash
# n-os-tr-smoketest — health check for n-OS-tr services.
# Extend with new sections as slices B (fips) and C (c-relay) land.

set -u

# -------------------- output helpers --------------------
if [[ -t 1 ]] && [[ "${NO_COLOR:-}" != "1" ]]; then
    C_PASS=$'\e[32m'
    C_FAIL=$'\e[31m'
    C_SKIP=$'\e[33m'
    C_HEAD=$'\e[1;36m'
    C_RST=$'\e[0m'
else
    C_PASS=''
    C_FAIL=''
    C_SKIP=''
    C_HEAD=''
    C_RST=''
fi

declare -i PASS=0 FAIL=0 SKIP=0

pass() { printf "  %s[PASS]%s  %-45s (%s)\n" "$C_PASS" "$C_RST" "$1" "${2:-ok}"; PASS+=1; }
fail() { printf "  %s[FAIL]%s  %-45s (%s)\n" "$C_FAIL" "$C_RST" "$1" "${2:-failed}"; FAIL+=1; }
skip() { printf "  %s[SKIP]%s  %-45s (%s)\n" "$C_SKIP" "$C_RST" "$1" "${2:-skipped}"; SKIP+=1; }
section() { printf "\n%s== %s ==%s\n" "$C_HEAD" "$1" "$C_RST"; }

# a convenience wrapper: runs a test command, passes if exit 0
# usage: check "label" command args...
check() {
    local label="$1"
    shift
    if "$@" >/dev/null 2>&1; then
        pass "$label" "$*"
    else
        local rc=$?
        fail "$label" "$* -> exit $rc"
    fi
}

# -------------------- core section ----------------------
section "core"

check "n-os-tr-firstboot active" systemctl is-active n-os-tr-firstboot.service
check "n-os-tr-firstboot succeeded" \
    bash -c '[[ "$(systemctl show -p Result --value n-os-tr-firstboot.service)" == "success" ]]'
check "firstboot marker exists" test -f /var/lib/n-os-tr/.provisioned
check "ginxsom nsec exists" test -f /var/lib/n-os-tr/keys/ginxsom.nsec
check "env file readable by www-data" \
    sudo -u www-data test -r /var/lib/n-os-tr/env

# -------------------- nginx + ginxsom --------------------
section "blossom (nginx + ginxsom)"

check "nginx active" systemctl is-active nginx.service
check "ginxsom active" systemctl is-active ginxsom.service
check "ginxsom socket exists" test -S /run/ginxsom/ginxsom-fcgi.sock

# HTTPS landing page
status=$(curl -sk -o /dev/null -w '%{http_code}' https://localhost/ 2>/dev/null)
if [[ "$status" == "200" ]]; then
    pass "landing page over TLS" "HTTP $status"
else
    fail "landing page over TLS" "HTTP $status"
fi

# BUD-01: HEAD on a random 64-hex should not explode (404 is fine, 5xx is not)
status=$(curl -sk -o /dev/null -w '%{http_code}' -I \
    https://localhost/0000000000000000000000000000000000000000000000000000000000000000 2>/dev/null)
case "$status" in
    200|404) pass "blob HEAD returns a non-5xx" "HTTP $status" ;;
    *)       fail "blob HEAD returns a non-5xx" "HTTP $status" ;;
esac

# -------------------- fips mesh daemon --------------------
section "fips mesh daemon"

check "fips.service active" systemctl is-active fips.service
check "fips-dns.service active" systemctl is-active fips-dns.service
check "fips0 interface present" ip link show fips0

npub=$(fipsctl show status 2>/dev/null | jq -r '.identity.npub // .npub // empty' | head -1 | tr -d '[:space:]')
case "$npub" in
    npub1*) pass "fipsctl status returns npub" "${npub:0:20}..." ;;
    *)      fail "fipsctl status returns npub" "got: ${npub:-<empty>}" ;;
esac

check "fips UDP bound on :2121" bash -c 'ss -ulnp 2>/dev/null | grep -q ":2121"'

# -------------------- c-relay nostr relay -----------------
section "c-relay nostr relay"

check "c-relay.service active" systemctl is-active c-relay.service
check "c-relay listening on :8888" bash -c 'ss -tlnp 2>/dev/null | grep -q ":8888"'

if journalctl -u c-relay.service --no-pager 2>/dev/null | grep -q "Admin Private Key:"; then
    pass "admin nsec logged in journal" "found"
elif ls /opt/c-relay/*.db >/dev/null 2>&1; then
    pass "admin nsec logged in journal" "relay initialized (db present)"
else
    fail "admin nsec logged in journal" "journal miss and no relay db"
fi

ws_status=$(curl -sk --http1.1 -o /dev/null -w '%{http_code}' \
    -H 'Connection: Upgrade' \
    -H 'Upgrade: websocket' \
    -H 'Sec-WebSocket-Version: 13' \
    -H 'Sec-WebSocket-Key: SGVsbG8sIHdvcmxkIQ==' \
    https://localhost/relay 2>/dev/null)
if [[ "$ws_status" == "101" ]]; then
    pass "wss://localhost/relay websocket upgrade" "HTTP $ws_status"
else
    fail "wss://localhost/relay websocket upgrade" "HTTP $ws_status"
fi

nip11=$(curl -sk -H 'Accept: application/nostr+json' https://localhost/relay 2>/dev/null)
if echo "$nip11" | jq -e '.name' >/dev/null 2>&1; then
    pass "NIP-11 info doc reachable" "name=$(echo "$nip11" | jq -r .name)"
else
    fail "NIP-11 info doc reachable" "no JSON .name"
fi

status=$(curl -sk -o /dev/null -w '%{http_code}' https://localhost/admin/ 2>/dev/null)
case "$status" in
    200|302|401) pass "admin UI reachable via nginx" "HTTP $status" ;;
    *)           fail "admin UI reachable via nginx" "HTTP $status" ;;
esac

# -------------------- summary ---------------------------
section "summary"
printf "  %s%d PASS%s   %s%d FAIL%s   %s%d SKIP%s\n" \
    "$C_PASS" "$PASS" "$C_RST" \
    "$C_FAIL" "$FAIL" "$C_RST" \
    "$C_SKIP" "$SKIP" "$C_RST"

if [[ $FAIL -gt 0 ]]; then
    exit 1
fi
exit 0
