#!/bin/sh
# ============================================================================
# SecuBox Swiss Army Knife - Unified Management & Recovery Tool
# Combines: mesh, recover, console, monitoring, and self-enhancement
# ============================================================================

VERSION="1.0.0"
SCRIPT_PATH="$(readlink -f "$0")"
SECUBOX_DIR="/srv/secubox"

# Colors
C_CYAN='\033[0;36m'
C_GREEN='\033[0;32m'
C_YELLOW='\033[1;33m'
C_RED='\033[0;31m'
C_BOLD='\033[1m'
C_NC='\033[0m'

banner() {
    echo "${C_CYAN}"
    cat << 'BANNER'
   _____ _____ _____ _   _ ____   _____  __
  / ____| ____/ ____| | | |  _ \ / _ \ \/ /
 | (___ |  _|| |    | | | | |_) | | | \  /
  \___ \| |__| |    | |_| |  _ <| |_| /  \
  ____) |____| |____| |_| | |_) \___/_/\_\
 |_____/______\_____|_____|____/
                                    SWISS
BANNER
    echo "${C_NC}"
    echo "${C_BOLD}SecuBox Swiss Army Knife v$VERSION${C_NC}"
    echo "Unified Management • Recovery • Mesh • Self-Enhancement"
    echo ""
}

# ============================================================================
# Tool Dispatch
# ============================================================================
tool_mesh() {
    exec /usr/sbin/secubox-mesh "$@"
}

tool_recover() {
    exec /usr/sbin/secubox-recover "$@"
}

tool_console() {
    if [ -f /usr/lib/secubox-console/secubox_console.py ]; then
        exec python3 /usr/lib/secubox-console/secubox_console.py "$@"
    else
        echo "Console not installed. Install with: opkg install secubox-console"
        exit 1
    fi
}

tool_mitm() {
    exec /usr/sbin/secubox-mitm-logs "$@"
}

# ============================================================================
# Quick Actions
# ============================================================================
action_status() {
    echo "${C_CYAN}=== SecuBox Status ===${C_NC}"
    echo ""

    # System
    echo "${C_BOLD}System:${C_NC}"
    echo "  Hostname: $(uci get system.@system[0].hostname 2>/dev/null || hostname)"
    echo "  Version:  $(cat /etc/secubox-version 2>/dev/null || echo 'unknown')"
    echo "  Uptime:   $(uptime | cut -d',' -f1 | cut -d' ' -f4-)"
    echo ""

    # Mesh
    echo "${C_BOLD}Mesh:${C_NC}"
    if [ -f /srv/secubox/mesh/node.id ]; then
        echo "  Node ID:  $(cat /srv/secubox/mesh/node.id)"
        echo "  Peers:    $(cat /srv/secubox/mesh/peers.json 2>/dev/null | jsonfilter -e '@.peers[*]' 2>/dev/null | wc -l)"
        echo "  Blocks:   $(find /srv/secubox/mesh/blocks -type f 2>/dev/null | wc -l)"
    else
        echo "  Not initialized. Run: secubox-swiss mesh init"
    fi
    echo ""

    # Recovery
    echo "${C_BOLD}Recovery:${C_NC}"
    echo "  Snapshots: $(ls /srv/secubox/recover/archives/*.tar.gz 2>/dev/null | wc -l)"
    echo "  Profiles:  $(ls /srv/secubox/recover/profiles/*.json 2>/dev/null | wc -l)"
    echo ""

    # Services
    echo "${C_BOLD}Key Services:${C_NC}"
    for svc in haproxy crowdsec mitmproxy; do
        if pgrep -x "$svc" >/dev/null 2>&1; then
            echo "  $svc: ${C_GREEN}running${C_NC}"
        else
            echo "  $svc: ${C_RED}stopped${C_NC}"
        fi
    done
}

action_backup() {
    local name="${1:-backup-$(date +%Y%m%d-%H%M%S)}"
    echo "${C_CYAN}Creating backup: $name${C_NC}"
    /usr/sbin/secubox-recover snapshot "$name"
}

action_reborn() {
    local output="${1:-/tmp/secubox-reborn.sh}"
    echo "${C_CYAN}Generating reborn script: $output${C_NC}"
    /usr/sbin/secubox-recover reborn "$output"
    echo ""
    echo "${C_GREEN}Reborn script ready!${C_NC}"
    echo "Copy to any machine and run to restore SecuBox."
}

action_sync() {
    echo "${C_CYAN}Syncing mesh...${C_NC}"
    /usr/sbin/secubox-mesh sync
    echo ""
    echo "${C_CYAN}Syncing recovery catalog...${C_NC}"
    /usr/sbin/secubox-recover apps-sync
}

action_health() {
    echo "${C_CYAN}=== Health Check ===${C_NC}"
    echo ""

    # Disk
    echo "${C_BOLD}Disk Usage:${C_NC}"
    df -h / /srv /opt 2>/dev/null | grep -v "^Filesystem"
    echo ""

    # Memory
    echo "${C_BOLD}Memory:${C_NC}"
    free -m 2>/dev/null || cat /proc/meminfo | head -3
    echo ""

    # Network
    echo "${C_BOLD}Network:${C_NC}"
    echo "  WAN IP: $(curl -s --connect-timeout 2 ifconfig.me 2>/dev/null || echo 'unavailable')"
    echo "  LAN IP: $(uci get network.lan.ipaddr 2>/dev/null)"
    echo ""

    # Security
    echo "${C_BOLD}Security:${C_NC}"
    if [ -f /var/log/secubox-access.log ]; then
        scans=$(grep -c '"is_scan":true' /var/log/secubox-access.log 2>/dev/null || echo 0)
        auths=$(grep -c '"is_auth_attempt":true' /var/log/secubox-access.log 2>/dev/null || echo 0)
        echo "  Scan attempts: $scans"
        echo "  Auth attempts: $auths"
    else
        echo "  MITM logging not active"
    fi
}

action_logs() {
    local component="${1:-all}"

    case "$component" in
        mitm)
            /usr/sbin/secubox-mitm-logs tail
            ;;
        mesh)
            cat /srv/secubox/mesh/chain.json 2>/dev/null | jsonfilter -e '@.blocks[-5:]' 2>/dev/null
            ;;
        security)
            /usr/sbin/secubox-mitm-logs scan
            ;;
        *)
            echo "${C_CYAN}=== Recent Logs ===${C_NC}"
            logread -l 30 2>/dev/null || tail -30 /var/log/messages 2>/dev/null
            ;;
    esac
}

# ============================================================================
# Self-Enhancement
# ============================================================================
action_self_update() {
    echo "${C_CYAN}Checking for updates...${C_NC}"

    # Check mesh peers for newer version
    local peers=$(cat /srv/secubox/mesh/peers.json 2>/dev/null | jsonfilter -e '@.peers[*].addr' 2>/dev/null)

    for peer in $peers; do
        echo "  Checking peer: $peer"
        local remote_ver=$(curl -s --connect-timeout 3 "http://$peer:7331/api/version" 2>/dev/null | jsonfilter -e '@.swiss' 2>/dev/null)

        if [ -n "$remote_ver" ] && [ "$remote_ver" != "$VERSION" ]; then
            echo "  ${C_YELLOW}Update available: $remote_ver${C_NC}"

            # Fetch and verify
            local update_hash=$(curl -s "http://$peer:7331/api/update/swiss/hash" 2>/dev/null)
            curl -s "http://$peer:7331/api/update/swiss" -o /tmp/secubox-swiss.new 2>/dev/null

            local local_hash=$(sha256sum /tmp/secubox-swiss.new 2>/dev/null | cut -d' ' -f1)

            if [ "$local_hash" = "$update_hash" ]; then
                echo "  ${C_GREEN}Hash verified. Installing...${C_NC}"
                chmod +x /tmp/secubox-swiss.new
                mv /tmp/secubox-swiss.new "$SCRIPT_PATH"
                echo "  ${C_GREEN}Updated to $remote_ver${C_NC}"
                exit 0
            else
                echo "  ${C_RED}Hash mismatch. Skipping.${C_NC}"
            fi
        fi
    done

    echo "  ${C_GREEN}Already up to date: $VERSION${C_NC}"
}

# ============================================================================
# Interactive Mode
# ============================================================================
interactive_menu() {
    while true; do
        clear
        banner
        echo "Quick Actions:"
        echo "  ${C_CYAN}1${C_NC}) Status       - System overview"
        echo "  ${C_CYAN}2${C_NC}) Backup       - Create snapshot"
        echo "  ${C_CYAN}3${C_NC}) Reborn       - Generate recovery script"
        echo "  ${C_CYAN}4${C_NC}) Sync         - Sync mesh & catalog"
        echo "  ${C_CYAN}5${C_NC}) Health       - Health check"
        echo "  ${C_CYAN}6${C_NC}) Logs         - View logs"
        echo "  ${C_CYAN}7${C_NC}) Update       - Self-update"
        echo ""
        echo "Tools:"
        echo "  ${C_CYAN}m${C_NC}) Mesh         - P2P mesh management"
        echo "  ${C_CYAN}r${C_NC}) Recover      - Recovery system"
        echo "  ${C_CYAN}c${C_NC}) Console      - Remote management (Python)"
        echo "  ${C_CYAN}s${C_NC}) Security     - MITM/Security logs"
        echo ""
        echo "  ${C_CYAN}q${C_NC}) Quit"
        echo ""
        printf "Choice: "
        read choice

        case "$choice" in
            1) action_status; read -p "Press Enter..." ;;
            2) action_backup; read -p "Press Enter..." ;;
            3) action_reborn; read -p "Press Enter..." ;;
            4) action_sync; read -p "Press Enter..." ;;
            5) action_health; read -p "Press Enter..." ;;
            6) action_logs; read -p "Press Enter..." ;;
            7) action_self_update; read -p "Press Enter..." ;;
            m) tool_mesh; break ;;
            r) tool_recover; break ;;
            c) tool_console; break ;;
            s) tool_mitm; break ;;
            q|Q) exit 0 ;;
            *) echo "Invalid choice" ;;
        esac
    done
}

# ============================================================================
# Main
# ============================================================================
case "$1" in
    # Quick actions
    status)
        action_status
        ;;
    backup)
        shift
        action_backup "$@"
        ;;
    reborn)
        shift
        action_reborn "$@"
        ;;
    sync)
        action_sync
        ;;
    health)
        action_health
        ;;
    logs)
        shift
        action_logs "$@"
        ;;
    update)
        action_self_update
        ;;

    # Tool dispatch
    mesh)
        shift
        tool_mesh "$@"
        ;;
    recover)
        shift
        tool_recover "$@"
        ;;
    console)
        shift
        tool_console "$@"
        ;;
    mitm|security)
        shift
        tool_mitm "$@"
        ;;

    # Version
    -v|--version|version)
        echo "SecuBox Swiss v$VERSION"
        ;;

    # Help
    -h|--help|help)
        banner
        echo "Usage: secubox-swiss [command] [args]"
        echo ""
        echo "Quick Actions:"
        echo "  status              System overview"
        echo "  backup [name]       Create snapshot"
        echo "  reborn [file]       Generate recovery script"
        echo "  sync                Sync mesh & catalog"
        echo "  health              Health check"
        echo "  logs [component]    View logs (mitm|mesh|security|all)"
        echo "  update              Self-update from mesh"
        echo ""
        echo "Tools:"
        echo "  mesh <cmd>          P2P mesh (init|peer-add|sync|...)"
        echo "  recover <cmd>       Recovery (snapshot|restore|profile-*|...)"
        echo "  console <cmd>       Remote management console"
        echo "  mitm <cmd>          Security/MITM logs"
        echo ""
        echo "Run without arguments for interactive menu."
        ;;

    # Interactive
    "")
        interactive_menu
        ;;

    *)
        echo "Unknown command: $1"
        echo "Run 'secubox-swiss help' for usage."
        exit 1
        ;;
esac
