#!/bin/sh
# Enhanced health check - JSON output (busybox only)

TOR_LOG="${TOR_LOG_DIR:-/var/log/tor}/notices.log"
TOR_DATA="${TOR_DATA_DIR:-/var/lib/tor}"

sanitize_num() {
    v=$(printf '%s' "$1" | tr -cd '0-9')
    [ -z "$v" ] && v=0
    printf '%s' "$v"
}

if ! pgrep -x tor >/dev/null 2>&1; then
    echo '{"status":"down","bootstrap":0,"reachable":"unknown","errors":0}'
    exit 1
fi

TOR_PID=$(pgrep -x tor)
TOR_PID=$(sanitize_num "$TOR_PID")
UPTIME=$(ps -o etime= -p "$TOR_PID" 2>/dev/null | tr -d ' ' || echo "unknown")

BOOTSTRAP=0
if [ -f "$TOR_LOG" ]; then
    if grep -q "Bootstrapped 100%" "$TOR_LOG"; then
        BOOTSTRAP=100
    else
        BOOTSTRAP=$(grep "Bootstrapped" "$TOR_LOG" | tail -1 | sed 's/.*Bootstrapped \([0-9]*\)%.*/\1/' 2>/dev/null || echo "0")
    fi
fi
BOOTSTRAP=$(sanitize_num "$BOOTSTRAP")

REACHABLE="unknown"
if [ -f "$TOR_LOG" ]; then
    if grep -q "Self-testing indicates your ORPort is reachable" "$TOR_LOG"; then
        REACHABLE="true"
    elif grep -q "ORPort is not reachable" "$TOR_LOG"; then
        REACHABLE="false"
    fi
fi

ERRORS=$(grep -c "\[err\]" "$TOR_LOG" 2>/dev/null || echo "0")
ERRORS=$(sanitize_num "$ERRORS")

NICKNAME="unknown"
FINGERPRINT="unknown"
if [ -f "$TOR_DATA/fingerprint" ]; then
    NICKNAME=$(cat "$TOR_DATA/fingerprint" | awk '{print $1}')
    FINGERPRINT=$(cat "$TOR_DATA/fingerprint" | awk '{print $2}')
fi

cat <<EOF
{
  "status": "up",
  "pid": $TOR_PID,
  "uptime": "$UPTIME",
  "bootstrap": $BOOTSTRAP,
  "reachable": "$REACHABLE",
  "errors": $ERRORS,
  "nickname": "$NICKNAME",
  "fingerprint": "$FINGERPRINT"
}
EOF