#!/bin/bash
# BDUSP DDoS Guard - CLI Tool (vg)

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BLUE='\033[0;34m'
NC='\033[0m'
BOLD='\033[1m'

BLOCKED_FILE="/var/lib/ddos-guard/blocked_ips.json"
QUARANTINE_FILE="/var/lib/ddos-guard/quarantine.json"
WHITELIST_FILE="/var/lib/ddos-guard/whitelist.json"
BLOCKLIST_FILE="/var/lib/ddos-guard/blocklist.json"
LOG_FILE="/var/log/ddos-guard.log"

print_header() {
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}  🛡️  BDUSP DDoS Guard${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

cmd_status() {
    print_header
    echo ""
    if systemctl is-active --quiet ddos-guard; then
        echo -e "  Service:    ${GREEN}● Running${NC}"
    else
        echo -e "  Service:    ${RED}● Stopped${NC}"
    fi

    # Count blocked IPs
    if [ -f "$BLOCKED_FILE" ]; then
        total=$(python3 -c "import json; d=json.load(open('$BLOCKED_FILE')); print(len(d))" 2>/dev/null || echo "0")
        perm=$(python3 -c "import json; d=json.load(open('$BLOCKED_FILE')); print(sum(1 for v in d.values() if v.get('permanent')))" 2>/dev/null || echo "0")
        echo -e "  Blocked:    ${RED}$total IP(s)${NC} ($perm permanent)"
    else
        echo -e "  Blocked:    ${GREEN}0 IP(s)${NC}"
    fi

    # Count quarantined domains
    if [ -f "$QUARANTINE_FILE" ]; then
        qcount=$(python3 -c "import json; d=json.load(open('$QUARANTINE_FILE')); print(len(d))" 2>/dev/null || echo "0")
        echo -e "  Quarantine: ${YELLOW}$qcount domain(s)${NC}"
    else
        echo -e "  Quarantine: ${GREEN}0 domain(s)${NC}"
    fi

    echo ""
    echo -e "  Uptime: $(systemctl show ddos-guard --property=ActiveEnterTimestamp | cut -d= -f2)"
    echo ""
}

cmd_blocked() {
    print_header
    echo -e "\n  ${BOLD}Blocked IPs:${NC}\n"

    if [ ! -f "$BLOCKED_FILE" ]; then
        echo -e "  ${GREEN}No blocked IPs.${NC}\n"
        return
    fi

    python3 << 'PYEOF'
import json, time, os

f = "/var/lib/ddos-guard/blocked_ips.json"
try:
    data = json.load(open(f))
except:
    print("  No data.")
    exit()

if not data:
    print("  No blocked IPs.")
    exit()

print(f"  {'IP':<20} {'Type':<12} {'Blocked At':<22} {'Expires'}")
print(f"  {'─'*20} {'─'*12} {'─'*22} {'─'*20}")

for ip, info in data.items():
    btype = "PERMANENT" if info.get("permanent") else "7 Days"
    blocked_at = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(info.get("time", 0)))
    if info.get("permanent"):
        expires = "Never"
    else:
        exp = info.get("time", 0) + info.get("duration", 0)
        expires = time.strftime("%Y-%m-%d %H:%M", time.localtime(exp))
    print(f"  {ip:<20} {btype:<12} {blocked_at:<22} {expires}")

print()
PYEOF
}

cmd_quarantine() {
    print_header
    echo -e "\n  ${BOLD}Quarantined Domains:${NC}\n"

    if [ ! -f "$QUARANTINE_FILE" ]; then
        echo -e "  ${GREEN}No quarantined domains.${NC}\n"
        return
    fi

    python3 << 'PYEOF'
import json, time

f = "/var/lib/ddos-guard/quarantine.json"
try:
    data = json.load(open(f))
except:
    print("  No data.")
    exit()

if not data:
    print("  No quarantined domains.")
    exit()

print(f"  {'Domain':<35} {'Since':<22} {'Docroot'}")
print(f"  {'─'*35} {'─'*22} {'─'*30}")

for domain, info in data.items():
    since = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(info.get("since", 0)))
    docroot = info.get("docroot", "Unknown")
    print(f"  {domain:<35} {since:<22} {docroot}")

print()
PYEOF
}

cmd_unblock() {
    local ip="$1"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg unblock <ip>${NC}"
        exit 1
    fi

    echo -e "${YELLOW}Unblocking $ip...${NC}"
    iptables -D INPUT -s "$ip" -j DROP 2>/dev/null
    iptables -D OUTPUT -d "$ip" -j DROP 2>/dev/null

    # Remove from JSON
    python3 << PYEOF
import json
f = "$BLOCKED_FILE"
try:
    data = json.load(open(f))
    data.pop("$ip", None)
    json.dump(data, open(f, "w"), indent=2)
    print("  Removed from block list.")
except:
    print("  Not found in block list.")
PYEOF

    echo -e "${GREEN}✅ $ip unblocked.${NC}"
}

cmd_release() {
    local domain="$1"
    if [ -z "$domain" ]; then
        echo -e "${RED}Usage: vg release <domain>${NC}"
        exit 1
    fi

    echo -e "${YELLOW}Releasing quarantine for $domain...${NC}"

    python3 << PYEOF
import json, os, shutil

f = "/var/lib/ddos-guard/quarantine.json"
try:
    data = json.load(open(f))
except:
    print("  No quarantine data found.")
    exit()

if "$domain" not in data:
    print("  Domain not in quarantine.")
    exit()

info = data["$domain"]
docroot = info.get("docroot")
if not docroot:
    print("  Docroot not found.")
    exit()

htaccess = os.path.join(docroot, ".htaccess")
backup   = os.path.join(docroot, ".htaccess.ddos_backup")
challenge = os.path.join(docroot, "ddos-challenge.php")
blocked_ips = os.path.join(docroot, ".ddos_blocked_ips.json")
verified_ips = os.path.join(docroot, ".ddos_verified_ips.json")

if os.path.exists(backup):
    shutil.move(backup, htaccess)
    print("  .htaccess restored.")
elif os.path.exists(htaccess):
    os.remove(htaccess)

for file in [challenge, blocked_ips, verified_ips]:
    if os.path.exists(file):
        os.remove(file)
        print(f"  Removed: {file}")

del data["$domain"]
json.dump(data, open(f, "w"), indent=2)
print("  Quarantine released.")
PYEOF

    echo -e "${GREEN}✅ $domain quarantine released.${NC}"
}

cmd_block() {
    local ip="$1"
    local duration="${2:-604800}"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg block <ip> [seconds]${NC}"
        exit 1
    fi

    iptables -I INPUT -s "$ip" -j DROP
    iptables -I OUTPUT -d "$ip" -j DROP

    python3 << PYEOF
import json, time, os
f = "/var/lib/ddos-guard/blocked_ips.json"
os.makedirs(os.path.dirname(f), exist_ok=True)
try:
    data = json.load(open(f))
except:
    data = {}
data["$ip"] = {"time": time.time(), "duration": $duration, "permanent": False, "label": "manual"}
json.dump(data, open(f, "w"), indent=2)
PYEOF

    echo -e "${GREEN}✅ $ip blocked for $duration seconds.${NC}"
}

cmd_whitelist_add() {
    local ip="$1"
    local note="${2:-manual}"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg whitelist-add <ip> [note]${NC}"
        exit 1
    fi
    python3 << PYEOF
import json, time, os
f = "/var/lib/ddos-guard/whitelist.json"
os.makedirs(os.path.dirname(f), exist_ok=True)
try:
    data = json.load(open(f))
except:
    data = {}
data["$ip"] = {"added": time.time(), "note": "$note"}
json.dump(data, open(f, "w"), indent=2)
print("  Added to whitelist.")
PYEOF
    echo -e "${GREEN}✅ $ip whitelisted. (IP block skipped, quarantine still triggers)${NC}"
}

cmd_whitelist_remove() {
    local ip="$1"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg whitelist-remove <ip>${NC}"
        exit 1
    fi
    python3 << PYEOF
import json
f = "/var/lib/ddos-guard/whitelist.json"
try:
    data = json.load(open(f))
    data.pop("$ip", None)
    json.dump(data, open(f, "w"), indent=2)
    print("  Removed from whitelist.")
except:
    print("  Not found in whitelist.")
PYEOF
    echo -e "${GREEN}✅ Done.${NC}"
}

cmd_whitelist_list() {
    print_header
    echo -e "\n  ${BOLD}Whitelisted IPs:${NC}"
    echo -e "  ${YELLOW}(These IPs won't be blocked, but quarantine still activates on flood)${NC}\n"

    python3 << 'PYEOF'
import json, time
f = "/var/lib/ddos-guard/whitelist.json"
defaults = ["127.0.0.1", "::1"]
try:
    data = json.load(open(f))
except:
    data = {}

all_ips = {ip: {"added": 0, "note": "system default"} for ip in defaults}
all_ips.update(data)

if not all_ips:
    print("  No whitelisted IPs.")
    exit()

print(f"  {'IP':<20} {'Added':<22} {'Note'}")
print(f"  {'─'*20} {'─'*22} {'─'*20}")
for ip, info in all_ips.items():
    added = time.strftime("%Y-%m-%d %H:%M", time.localtime(info.get("added", 0))) if info.get("added") else "system"
    note = info.get("note", "")
    print(f"  {ip:<20} {added:<22} {note}")
print()
PYEOF
}

cmd_blocklist_add() {
    local ip="$1"
    local note="${2:-manual}"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg blocklist-add <ip> [note]${NC}"
        exit 1
    fi

    # Immediately block via iptables
    iptables -I INPUT -s "$ip" -j DROP 2>/dev/null
    iptables -I OUTPUT -d "$ip" -j DROP 2>/dev/null

    python3 << PYEOF
import json, time, os
f = "/var/lib/ddos-guard/blocklist.json"
os.makedirs(os.path.dirname(f), exist_ok=True)
try:
    data = json.load(open(f))
except:
    data = {}
data["$ip"] = {"added": time.time(), "note": "$note", "permanent": True}
json.dump(data, open(f, "w"), indent=2)
print("  Added to permanent blocklist.")
PYEOF
    echo -e "${GREEN}✅ $ip permanently blocked and added to blocklist.${NC}"
}

cmd_blocklist_remove() {
    local ip="$1"
    if [ -z "$ip" ]; then
        echo -e "${RED}Usage: vg blocklist-remove <ip>${NC}"
        exit 1
    fi

    iptables -D INPUT -s "$ip" -j DROP 2>/dev/null
    iptables -D OUTPUT -d "$ip" -j DROP 2>/dev/null

    python3 << PYEOF
import json
f = "/var/lib/ddos-guard/blocklist.json"
try:
    data = json.load(open(f))
    data.pop("$ip", None)
    json.dump(data, open(f, "w"), indent=2)
    print("  Removed from blocklist.")
except:
    print("  Not found in blocklist.")
PYEOF
    echo -e "${GREEN}✅ $ip removed from blocklist and unblocked.${NC}"
}

cmd_blocklist_list() {
    print_header
    echo -e "\n  ${BOLD}Permanent Blocklist:${NC}\n"

    python3 << 'PYEOF'
import json, time
f = "/var/lib/ddos-guard/blocklist.json"
try:
    data = json.load(open(f))
except:
    data = {}

if not data:
    print("  No IPs in blocklist.")
    exit()

print(f"  {'IP':<20} {'Added':<22} {'Note'}")
print(f"  {'─'*20} {'─'*22} {'─'*20}")
for ip, info in data.items():
    added = time.strftime("%Y-%m-%d %H:%M", time.localtime(info.get("added", 0)))
    note = info.get("note", "")
    print(f"  {ip:<20} {added:<22} {note}")
print()
PYEOF
}

cmd_log() {
    echo -e "${CYAN}━━━━ Live Log (Ctrl+C to exit) ━━━━${NC}"
    tail -f "$LOG_FILE"
}

cmd_restart() {
    systemctl restart ddos-guard
    echo -e "${GREEN}✅ Service restarted.${NC}"
}

cmd_stop() {
    systemctl stop ddos-guard
    echo -e "${YELLOW}⏹ Service stopped.${NC}"
}

cmd_start() {
    systemctl start ddos-guard
    echo -e "${GREEN}▶ Service started.${NC}"
}

cmd_help() {
    print_header
    echo ""
    echo -e "  ${BOLD}Usage:${NC} vg <command> [args]"
    echo ""
    echo -e "  ${CYAN}Monitoring:${NC}"
    echo -e "    ${GREEN}status${NC}                  Service status + summary"
    echo -e "    ${GREEN}blocked${NC}                 List auto-blocked IPs"
    echo -e "    ${GREEN}quarantine${NC}              List quarantined domains"
    echo -e "    ${GREEN}log${NC}                     Live log stream"
    echo ""
    echo -e "  ${CYAN}IP Actions:${NC}"
    echo -e "    ${GREEN}block${NC} <ip>              Manually block an IP (7 days)"
    echo -e "    ${GREEN}unblock${NC} <ip>            Unblock an IP"
    echo ""
    echo -e "  ${CYAN}Whitelist (block skipped, quarantine still triggers):${NC}"
    echo -e "    ${GREEN}whitelist-add${NC} <ip> [note]"
    echo -e "    ${GREEN}whitelist-remove${NC} <ip>"
    echo -e "    ${GREEN}whitelist${NC}               Show whitelist"
    echo ""
    echo -e "  ${CYAN}Blocklist (permanent, survives reboot):${NC}"
    echo -e "    ${GREEN}blocklist-add${NC} <ip> [note]"
    echo -e "    ${GREEN}blocklist-remove${NC} <ip>"
    echo -e "    ${GREEN}blocklist${NC}               Show blocklist"
    echo ""
    echo -e "  ${CYAN}Domain:${NC}"
    echo -e "    ${GREEN}release${NC} <domain>        Release domain from quarantine"
    echo ""
    echo -e "  ${CYAN}Service:${NC}"
    echo -e "    ${GREEN}start${NC} / ${GREEN}stop${NC} / ${GREEN}restart${NC}"
    echo ""
}

# ─── ROUTER ───────────────────────────────────────────────────────────────────

case "$1" in
    status)           cmd_status ;;
    blocked)          cmd_blocked ;;
    quarantine)       cmd_quarantine ;;
    unblock)          cmd_unblock "$2" ;;
    release)          cmd_release "$2" ;;
    block)            cmd_block "$2" "$3" ;;
    whitelist-add)    cmd_whitelist_add "$2" "$3" ;;
    whitelist-remove) cmd_whitelist_remove "$2" ;;
    whitelist)        cmd_whitelist_list ;;
    blocklist-add)    cmd_blocklist_add "$2" "$3" ;;
    blocklist-remove) cmd_blocklist_remove "$2" ;;
    blocklist)        cmd_blocklist_list ;;
    log)              cmd_log ;;
    restart)          cmd_restart ;;
    stop)             cmd_stop ;;
    start)            cmd_start ;;
    help|--help|-h)   cmd_help ;;
    *)                cmd_help ;;
esac
