#!/bin/sh
# Enhanced status check (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"
}

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🧅 Tor Relay Status"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""

if pgrep -x tor >/dev/null 2>&1; then
    TOR_PID=$(pgrep -x tor)
    echo "🚀 Status:      RUNNING (PID: $TOR_PID)"
else
    echo "❌ Status:      STOPPED"
    echo ""
    exit 1
fi

if [ ! -f "$TOR_LOG" ]; then
    echo "⚠️  Log:         NOT FOUND"
    echo ""
    exit 1
fi

if grep -q "Bootstrapped 100%" "$TOR_LOG" 2>/dev/null; then
    echo "✅ Bootstrap:   100% COMPLETE"
else
    PROGRESS=$(grep "Bootstrapped" "$TOR_LOG" 2>/dev/null | tail -1 | sed 's/.*Bootstrapped \([0-9]*\)%.*/\1/' 2>/dev/null || echo "0")
    PROGRESS=$(sanitize_num "$PROGRESS")
    echo "⏳ Bootstrap:   ${PROGRESS}%"
fi

if grep -q "Self-testing indicates your ORPort is reachable" "$TOR_LOG"; then
    echo "🌐 ORPort:      REACHABLE"
elif grep -q "ORPort is not reachable" "$TOR_LOG"; then
    echo "⚠️  ORPort:      NOT REACHABLE"
else
    echo "❓ ORPort:      TESTING..."
fi

if [ -f "$TOR_DATA/fingerprint" ] && [ -r "$TOR_DATA/fingerprint" ]; then
    FINGERPRINT=$(cat "$TOR_DATA/fingerprint" | awk '{print $2}')
    NICKNAME=$(cat "$TOR_DATA/fingerprint" | awk '{print $1}')
    echo "🪪 Nickname:    $NICKNAME"

    FP_START=$(printf "%s" "$FINGERPRINT" | cut -c1-8)
    FP_END=$(printf "%s" "$FINGERPRINT" | cut -c33-40)
    echo "🔑 Fingerprint: ${FP_START}...${FP_END}"
fi

# Happy Family status
FAMILY_KEY_COUNT=0
if [ -d "$TOR_DATA/keys" ]; then
    for fk in "$TOR_DATA/keys"/*.secret_family_key; do
        [ -f "$fk" ] || continue
        FAMILY_KEY_COUNT=$((FAMILY_KEY_COUNT + 1))
    done
fi
TORRC="${TOR_CONFIG:-/etc/tor/torrc}"
if [ "$FAMILY_KEY_COUNT" -gt 0 ]; then
    echo "👨‍👩‍👧 Family Key: $FAMILY_KEY_COUNT key(s) present"
fi
if [ -f "$TORRC" ] && grep -qi "^FamilyId " "$TORRC" 2>/dev/null; then
    echo "✅ Happy Family: CONFIGURED"
elif [ "$FAMILY_KEY_COUNT" -gt 0 ]; then
    echo "⚠️  Happy Family: key present but FamilyId not in torrc"
fi

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

if [ "$ERRORS" -gt 0 ]; then
    echo "❌ Errors:      $ERRORS (check logs)"
else
    echo "✅ Errors:      0"
fi

if [ "$WARNINGS" -gt 5 ]; then
    echo "⚠️  Warnings:    $WARNINGS"
fi

UPTIME=$(ps -o etime= -p "$TOR_PID" 2>/dev/null | tr -d ' ' || echo "unknown")
[ -n "$UPTIME" ] && echo "⏱️  Uptime:      $UPTIME"

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "💡 Tip: Use 'docker logs -f <container>' for live logs"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""