#!/bin/bash
# SecuBox CLI - Main command interface
# CyberMind - https://cybermind.fr

set -euo pipefail

VERSION="2.0.0"
SECUBOX_SERVICES=$(systemctl list-units --type=service --all 'secubox-*' --no-legend 2>/dev/null | awk '{print $1}' | sed 's/.service$//')

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

usage() {
    cat <<EOF
${CYAN}SecuBox${NC} - Security Appliance CLI v${VERSION}

${YELLOW}Usage:${NC}
    secubox <command> [options]

${YELLOW}System:${NC}
    status          Show system and services status
    services        List all SecuBox services
    info            Show system information
    logs [service]  View logs (all or specific service)
    version         Show version information

${YELLOW}Security:${NC}
    threats         View blocked threats (CrowdSec + WAF)
    waf             WAF inspection status
    firewall        Firewall rules (nftables)
    bans            CrowdSec active bans

${YELLOW}Network:${NC}
    network         Show network configuration
    vhosts          HAProxy virtual hosts
    certs           SSL certificate status

${YELLOW}Control:${NC}
    restart <svc>   Restart a SecuBox service
    start <svc>     Start a SecuBox service
    stop <svc>      Stop a SecuBox service
    mode [kiosk|tui|console]  Switch display mode
    acme-renew <domain>       Renew SSL certificate
    help            Show this help message

${YELLOW}Examples:${NC}
    secubox status
    secubox logs crowdsec
    secubox restart wireguard

EOF
}

cmd_version() {
    echo -e "${CYAN}SecuBox${NC} v${VERSION}"
    echo -e "Debian $(cat /etc/debian_version 2>/dev/null || echo 'unknown')"
    echo -e "Kernel $(uname -r)"
    if [[ -f /etc/secubox/board ]]; then
        echo -e "Board: $(cat /etc/secubox/board)"
    fi
}

cmd_status() {
    echo -e "${CYAN}=== SecuBox Status ===${NC}"
    echo

    # Uptime
    echo -e "${YELLOW}Uptime:${NC} $(uptime -p 2>/dev/null || uptime)"

    # Memory
    echo -e "${YELLOW}Memory:${NC} $(free -h | awk '/^Mem:/ {print $3 "/" $2}')"

    # Disk
    echo -e "${YELLOW}Disk:${NC} $(df -h / | awk 'NR==2 {print $3 "/" $2 " (" $5 " used)"}')"

    # Load
    echo -e "${YELLOW}Load:${NC} $(cat /proc/loadavg | awk '{print $1, $2, $3}')"

    echo
    echo -e "${CYAN}=== Services ===${NC}"

    # List secubox services status
    systemctl list-units --type=service 'secubox-*' --no-legend 2>/dev/null | while read -r line; do
        unit=$(echo "$line" | awk '{print $1}')
        state=$(echo "$line" | awk '{print $3}')
        sub=$(echo "$line" | awk '{print $4}')
        name=$(echo "$unit" | sed 's/secubox-//' | sed 's/.service$//')

        if [[ "$state" == "active" ]]; then
            echo -e "  ${GREEN}●${NC} ${name}: ${GREEN}${sub}${NC}"
        else
            echo -e "  ${RED}○${NC} ${name}: ${RED}${state}${NC}"
        fi
    done

    # Count
    total=$(systemctl list-units --type=service --all 'secubox-*' --no-legend 2>/dev/null | wc -l)
    active=$(systemctl list-units --type=service 'secubox-*' --no-legend 2>/dev/null | grep -c "active running" || true)
    echo
    echo -e "${YELLOW}Total:${NC} ${active}/${total} services running"
}

cmd_services() {
    echo -e "${CYAN}=== SecuBox Services ===${NC}"
    systemctl list-units --type=service --all 'secubox-*' --no-pager 2>/dev/null || echo "No services found"
}

cmd_logs() {
    local service="${1:-}"
    if [[ -z "$service" ]]; then
        journalctl -u 'secubox-*' -f --no-pager
    else
        journalctl -u "secubox-${service}.service" -f --no-pager
    fi
}

cmd_restart() {
    local service="${1:-}"
    if [[ -z "$service" ]]; then
        echo -e "${RED}Error:${NC} Service name required"
        echo "Usage: secubox restart <service>"
        exit 1
    fi
    echo -e "${YELLOW}Restarting${NC} secubox-${service}..."
    systemctl restart "secubox-${service}.service"
    echo -e "${GREEN}Done${NC}"
}

cmd_start() {
    local service="${1:-}"
    if [[ -z "$service" ]]; then
        echo -e "${RED}Error:${NC} Service name required"
        exit 1
    fi
    echo -e "${YELLOW}Starting${NC} secubox-${service}..."
    systemctl start "secubox-${service}.service"
    echo -e "${GREEN}Done${NC}"
}

cmd_stop() {
    local service="${1:-}"
    if [[ -z "$service" ]]; then
        echo -e "${RED}Error:${NC} Service name required"
        exit 1
    fi
    echo -e "${YELLOW}Stopping${NC} secubox-${service}..."
    systemctl stop "secubox-${service}.service"
    echo -e "${GREEN}Done${NC}"
}

cmd_info() {
    echo -e "${CYAN}=== System Information ===${NC}"
    echo
    echo -e "${YELLOW}Hostname:${NC} $(hostname)"
    echo -e "${YELLOW}OS:${NC} $(cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d '"')"
    echo -e "${YELLOW}Kernel:${NC} $(uname -r)"
    echo -e "${YELLOW}Architecture:${NC} $(uname -m)"

    if [[ -f /etc/secubox/board ]]; then
        echo -e "${YELLOW}Board:${NC} $(cat /etc/secubox/board)"
    fi

    if command -v lscpu &>/dev/null; then
        echo -e "${YELLOW}CPU:${NC} $(lscpu | grep 'Model name' | cut -d: -f2 | xargs)"
        echo -e "${YELLOW}Cores:${NC} $(nproc)"
    fi

    echo -e "${YELLOW}Memory:${NC} $(free -h | awk '/^Mem:/ {print $2}')"
    echo -e "${YELLOW}Disk:${NC} $(df -h / | awk 'NR==2 {print $2}')"
}

cmd_network() {
    echo -e "${CYAN}=== Network Configuration ===${NC}"
    echo

    # IP addresses
    echo -e "${YELLOW}IP Addresses:${NC}"
    ip -4 addr show | grep inet | grep -v '127.0.0.1' | awk '{print "  " $NF ": " $2}'

    echo
    echo -e "${YELLOW}Default Route:${NC}"
    ip route show default 2>/dev/null | head -1 || echo "  No default route"

    echo
    echo -e "${YELLOW}DNS:${NC}"
    grep -v '^#' /etc/resolv.conf 2>/dev/null | grep nameserver | awk '{print "  " $2}' || echo "  Not configured"

    echo
    echo -e "${YELLOW}Interfaces:${NC}"
    ip link show | grep -E '^[0-9]+:' | awk -F: '{print "  " $2}' | xargs -n1
}

cmd_threats() {
    echo -e "${CYAN}=== SecuBox Threats ===${NC}"
    echo
    echo -e "${YELLOW}CrowdSec Active Bans:${NC}"
    cscli decisions list --limit 10 2>/dev/null | tail -12 || echo "  CrowdSec not running"
    echo
    echo -e "${YELLOW}WAF Recent Threats:${NC}"
    if [[ -f /srv/mitmproxy/logs/waf-threats.log ]]; then
        tail -5 /srv/mitmproxy/logs/waf-threats.log | jq -r '"\(.timestamp) | \(.client_ip) | \(.category) | \(.action)"' 2>/dev/null || tail -5 /srv/mitmproxy/logs/waf-threats.log
    else
        echo "  No WAF threats logged"
    fi
}

cmd_waf() {
    echo -e "${CYAN}=== SecuBox WAF Status ===${NC}"
    echo
    LXC_STATUS=$(lxc-info -n mitmproxy -s 2>/dev/null | grep -oP "State:\s+\K\w+" || echo "UNKNOWN")
    if [[ "$LXC_STATUS" == "RUNNING" ]]; then
        echo -e "  ${GREEN}●${NC} mitmproxy LXC: ${GREEN}RUNNING${NC}"
    else
        echo -e "  ${RED}●${NC} mitmproxy LXC: ${RED}$LXC_STATUS${NC}"
    fi
    if [[ -f /srv/mitmproxy/logs/waf-threats.log ]]; then
        TOTAL=$(wc -l < /srv/mitmproxy/logs/waf-threats.log 2>/dev/null || echo 0)
        echo -e "  Total Threats Logged: ${CYAN}$TOTAL${NC}"
    fi
    VHOSTS=$(grep -c "use_backend mitmproxy_inspector" /etc/haproxy/haproxy.cfg 2>/dev/null || echo 0)
    echo -e "  Vhosts via WAF: ${CYAN}$VHOSTS${NC}"
}

cmd_firewall() {
    echo -e "${CYAN}=== SecuBox Firewall (nftables) ===${NC}"
    echo
    echo -e "${YELLOW}Tables:${NC}"
    nft list tables 2>/dev/null || echo "  nftables not active"
    echo
    echo -e "${YELLOW}Active Connections:${NC}"
    ss -tuln | head -15
}

cmd_bans() {
    echo -e "${CYAN}=== CrowdSec Active Bans ===${NC}"
    cscli decisions list --limit 20 2>/dev/null || echo "CrowdSec not running"
}

cmd_vhosts() {
    echo -e "${CYAN}=== HAProxy Virtual Hosts ===${NC}"
    COUNT=$(grep -c "^    acl host_" /etc/haproxy/haproxy.cfg 2>/dev/null || echo 0)
    echo -e "  Total vhosts: ${GREEN}$((COUNT/2))${NC}"
    echo
    echo -e "${YELLOW}Recent vhosts:${NC}"
    grep "hdr(host) -i" /etc/haproxy/haproxy.cfg 2>/dev/null | tail -10 | awk '{print "  " $NF}'
}

cmd_certs() {
    echo -e "${CYAN}=== SSL Certificates ===${NC}"
    echo
    for cert in /data/haproxy/certs/*.pem; do
        [[ ! -f "$cert" ]] && continue
        name=$(basename "$cert")
        if openssl x509 -in "$cert" -noout -checkend 0 2>/dev/null; then
            echo -e "  ${GREEN}✓${NC} $name"
        else
            echo -e "  ${RED}✗${NC} $name ${RED}EXPIRED${NC}"
        fi
    done 2>/dev/null | head -20
    echo
    TOTAL=$(ls /data/haproxy/certs/*.pem 2>/dev/null | wc -l)
    echo -e "  Total: $TOTAL certificates"
}

cmd_mode() {
    local mode="${1:-}"
    MODE_DIR="/var/lib/secubox"
    mkdir -p "$MODE_DIR"
    case "$mode" in
        kiosk)
            rm -f "$MODE_DIR/.tui-enabled"
            touch "$MODE_DIR/.kiosk-enabled"
            echo -e "${GREEN}Switched to KIOSK mode${NC}"
            echo "Restart required: systemctl restart secubox-ui-manager"
            ;;
        tui)
            rm -f "$MODE_DIR/.kiosk-enabled"
            touch "$MODE_DIR/.tui-enabled"
            echo -e "${GREEN}Switched to TUI mode${NC}"
            echo "Restart required: systemctl restart secubox-ui-manager"
            ;;
        console)
            rm -f "$MODE_DIR/.kiosk-enabled" "$MODE_DIR/.tui-enabled"
            echo -e "${GREEN}Switched to CONSOLE mode${NC}"
            ;;
        *)
            if [[ -f "$MODE_DIR/.kiosk-enabled" ]]; then
                echo "Current mode: kiosk"
            elif [[ -f "$MODE_DIR/.tui-enabled" ]]; then
                echo "Current mode: tui"
            else
                echo "Current mode: console"
            fi
            echo "Usage: secubox mode [kiosk|tui|console]"
            ;;
    esac
}

cmd_acme_renew() {
    local domain="${1:-}"
    if [[ -z "$domain" ]]; then
        echo "Usage: secubox acme-renew <domain>"
        echo
        echo "Available certificates:"
        ~/.acme.sh/acme.sh --list 2>/dev/null | tail -n +2 | awk '{print "  " $1}'
        return 1
    fi
    echo "Renewing certificate for $domain..."
    ~/.acme.sh/acme.sh --renew -d "$domain" --force
    cat ~/.acme.sh/${domain}_ecc/fullchain.cer ~/.acme.sh/${domain}_ecc/${domain}.key \
        > /data/haproxy/certs/${domain}.pem 2>/dev/null && \
        systemctl reload haproxy && \
        echo -e "${GREEN}Certificate deployed to HAProxy${NC}"
}

# Main
case "${1:-help}" in
    status)
        cmd_status
        ;;
    services)
        cmd_services
        ;;
    version|-v|--version)
        cmd_version
        ;;
    logs|log)
        cmd_logs "${2:-}"
        ;;
    restart)
        cmd_restart "${2:-}"
        ;;
    start)
        cmd_start "${2:-}"
        ;;
    stop)
        cmd_stop "${2:-}"
        ;;
    info)
        cmd_info
        ;;
    network|net)
        cmd_network
        ;;
    threats)
        cmd_threats
        ;;
    waf)
        cmd_waf
        ;;
    firewall|fw)
        cmd_firewall
        ;;
    bans)
        cmd_bans
        ;;
    vhosts)
        cmd_vhosts
        ;;
    certs)
        cmd_certs
        ;;
    mode)
        cmd_mode "${2:-}"
        ;;
    acme-renew)
        cmd_acme_renew "${2:-}"
        ;;
    help|-h|--help|*)
        usage
        ;;
esac
