#!/bin/bash
# BDUSP DDoS Guard CLI v6 - Smart Quarantine Edition

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

BASE="/var/lib/ddos-guard"
BLOCKLIST="$BASE/blocklist.json"
STATE="$BASE/state.json"
WHITELIST="$BASE/whitelist.json"
CONFIG="$BASE/config.json"
LOGFILE="/var/log/ddos-guard.log"
IPSET_BLOCKLIST="ddosguard_blocklist"

header() {
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "${CYAN}  🛡️  BDUSP DDoS Guard v6 — Smart Quarantine${NC}"
    echo -e "${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
}

py() { python3 -c "$1"; }

valid_ip() {
    python3 -c "
import re,sys
ip='$1'.strip()
m=re.match(r'^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$',ip)
if m and all(0<=int(g)<=255 for g in m.groups()): sys.exit(0)
sys.exit(1)
" 2>/dev/null
}

DEFAULTS_PY="{'window_seconds':30,'block_threshold':3000,'perm_threshold':5000,'check_interval':10,'quarantine_on_threshold':1500,'quarantine_off_threshold':400,'quarantine_off_consecutive':3,'quarantine_mode':'auto','quarantine_window_seconds':10,'quarantine_check_interval':10,'quarantine_block_threshold':300,'quarantine_perm_threshold':500,'domlog_rescan_interval':60,'expiry_check_every_n':6}"

CONFIG_KEYS="window_seconds block_threshold perm_threshold check_interval quarantine_on_threshold quarantine_off_threshold quarantine_off_consecutive quarantine_mode quarantine_window_seconds quarantine_check_interval quarantine_block_threshold quarantine_perm_threshold domlog_rescan_interval expiry_check_every_n"

BOUNDS_PY="{'window_seconds':(5,3600),'block_threshold':(10,1000000),'perm_threshold':(10,1000000),'check_interval':(3,120),'quarantine_on_threshold':(10,1000000),'quarantine_off_threshold':(5,1000000),'quarantine_off_consecutive':(1,50),'quarantine_window_seconds':(3,600),'quarantine_check_interval':(2,60),'quarantine_block_threshold':(5,100000),'quarantine_perm_threshold':(5,1000000),'domlog_rescan_interval':(10,3600),'expiry_check_every_n':(1,200)}"

cfg_get() {
    py "
import json
try: d=json.load(open('$CONFIG'))
except: d={}
defs=$DEFAULTS_PY
defs.update(d); print(defs.get('$1',''))
"
}

# ── batch ipset helpers (একাধিক IP একসাথে হলেও single subprocess call) ──
ipset_batch_del() {
    local set="$1"; shift
    local ips=("$@")
    [ ${#ips[@]} -eq 0 ] && return
    { for ip in "${ips[@]}"; do echo "del $set $ip -exist"; done; } | ipset restore -! 2>/dev/null
}

ipset_batch_add() {
    local set="$1"; shift
    local ips=("$@")
    [ ${#ips[@]} -eq 0 ] && return
    { for ip in "${ips[@]}"; do echo "add $set $ip -exist"; done; } | ipset restore -! 2>/dev/null
}

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

    qmode=$(cfg_get quarantine_mode)
    qactive=$(py "
import json
try: s=json.load(open('$STATE'))
except: s={}
print('yes' if s.get('quarantine_active') else 'no')
")
    last_total=$(py "
import json
try: s=json.load(open('$STATE'))
except: s={}
print(s.get('last_cycle_total','-'))
")

    if [ "$qactive" == "yes" ]; then
        echo -e "  Quarantine  : ${RED}● ACTIVE${NC}  (mode: $qmode)"
        echo -e "                ${YELLOW}↳ এখন strict per-IP threshold প্রয়োগ হচ্ছে (নিচে দেখুন)${NC}"
    else
        echo -e "  Quarantine  : ${GREEN}● inactive${NC}  (mode: $qmode)"
    fi
    echo -e "  Last global rate : ${last_total} req/$(cfg_get check_interval)s"

    total=$(py "import json
try: d=json.load(open('$BLOCKLIST')); print(len(d))
except: print(0)")
    temp=$(py "import json
try: d=json.load(open('$BLOCKLIST')); print(sum(1 for v in d.values() if not v.get('permanent')))
except: print(0)")
    perm=$(py "import json
try: d=json.load(open('$BLOCKLIST')); print(sum(1 for v in d.values() if v.get('permanent')))
except: print(0)")
    qtagged=$(py "import json
try: d=json.load(open('$BLOCKLIST')); print(sum(1 for v in d.values() if 'quarantine' in v.get('label','')))
except: print(0)")
    wl=$(py "import json
try: d=json.load(open('$WHITELIST')); print(len(d))
except: print(0)")

    echo -e "  Blocked     : ${RED}${total} IP(s)${NC} — ${temp} temp(7d), ${perm} permanent (${qtagged} quarantine-triggered)"
    echo -e "  Whitelist   : ${GREEN}${wl} IP(s)${NC}"
    echo ""
    echo -e "  ${BOLD}Normal per-IP thresholds (quarantine OFF, per $(cfg_get window_seconds)s window):${NC}"
    echo -e "  7-day block            : $(cfg_get block_threshold) requests"
    echo -e "  Permanent block        : $(cfg_get perm_threshold) requests"
    echo -e "  Check interval         : $(cfg_get check_interval)s"
    echo ""
    echo -e "  ${BOLD}Quarantine per-IP thresholds (quarantine ON, per $(cfg_get quarantine_window_seconds)s window):${NC}"
    echo -e "  7-day block            : $(cfg_get quarantine_block_threshold) requests  ${YELLOW}(strict)${NC}"
    echo -e "  Permanent block        : $(cfg_get quarantine_perm_threshold) requests  ${YELLOW}(strict)${NC}"
    echo -e "  Check interval         : $(cfg_get quarantine_check_interval)s  ${YELLOW}(independent থেকে normal interval)${NC}"
    echo ""
    echo -e "  ${BOLD}Quarantine ON/OFF trigger (global, সব IP মিলিয়ে, per $(cfg_get check_interval)s):${NC}"
    echo -e "  Quarantine ON  ≥        : $(cfg_get quarantine_on_threshold) total req"
    echo -e "  Quarantine OFF ≤        : $(cfg_get quarantine_off_threshold) total req"
    echo -e "  OFF consecutive checks  : $(cfg_get quarantine_off_consecutive)"
    echo ""
}

# ── vg config ─────────────────────────────────────────────────────────────────
cmd_config() {
    if [ -z "$1" ]; then
        header; echo ""
        echo -e "  ${BOLD}— Normal mode (quarantine OFF) —${NC}"
        echo -e "  ${GREEN}window_seconds${NC}               $(cfg_get window_seconds)      Per-IP monitoring window (sec)"
        echo -e "  ${GREEN}block_threshold${NC}              $(cfg_get block_threshold)     Per-IP requests → 7-day block"
        echo -e "  ${GREEN}perm_threshold${NC}               $(cfg_get perm_threshold)      Per-IP requests → permanent block"
        echo -e "  ${GREEN}check_interval${NC}               $(cfg_get check_interval)      Log check every N seconds"
        echo ""
        echo -e "  ${YELLOW}— Quarantine trigger (global aggregate rate) —${NC}"
        echo -e "  ${GREEN}quarantine_on_threshold${NC}      $(cfg_get quarantine_on_threshold)    Global req/interval → quarantine ON"
        echo -e "  ${GREEN}quarantine_off_threshold${NC}     $(cfg_get quarantine_off_threshold)     Global req/interval → counts as normal"
        echo -e "  ${GREEN}quarantine_off_consecutive${NC}   $(cfg_get quarantine_off_consecutive)       Consecutive normal checks → quarantine OFF"
        echo -e "  ${GREEN}quarantine_mode${NC}              $(cfg_get quarantine_mode)    auto | on | off (manual override)"
        echo ""
        echo -e "  ${YELLOW}— Quarantine mode per-IP rules (stricter, quarantine ON থাকলে কার্যকর) —${NC}"
        echo -e "  ${GREEN}quarantine_window_seconds${NC}    $(cfg_get quarantine_window_seconds)      Per-IP monitoring window quarantine এ"
        echo -e "  ${GREEN}quarantine_check_interval${NC}    $(cfg_get quarantine_check_interval)      Log check interval quarantine এ (normal থেকে independent)"
        echo -e "  ${GREEN}quarantine_block_threshold${NC}   $(cfg_get quarantine_block_threshold)     Per-IP requests → 7-day block (quarantine এ)"
        echo -e "  ${GREEN}quarantine_perm_threshold${NC}    $(cfg_get quarantine_perm_threshold)     Per-IP requests → permanent block (quarantine এ)"
        echo ""
        echo -e "  ${YELLOW}— Performance tuning —${NC}"
        echo -e "  ${GREEN}domlog_rescan_interval${NC}       $(cfg_get domlog_rescan_interval)      কত সেকেন্ড পর পর domlog ফোল্ডার re-scan হবে"
        echo -e "  ${GREEN}expiry_check_every_n${NC}         $(cfg_get expiry_check_every_n)        প্রতি কত cycle পর পর expired block চেক হবে"
        echo ""
        echo -e "  ${YELLOW}Usage: vg config <key> <value>${NC}"
        echo -e "  Example: vg config quarantine_block_threshold 200"
        echo -e "  Example: vg config quarantine_check_interval 5"
        echo ""
        return
    fi
    [ -z "$2" ] && echo -e "${RED}Usage: vg config <key> <value>${NC}" && exit 1

    key="$1"
    found=0
    for k in $CONFIG_KEYS; do [ "$k" == "$key" ] && found=1; done
    if [ "$found" -eq 0 ]; then
        echo -e "${RED}Unknown key: $key${NC}"
        echo -e "Valid keys: $CONFIG_KEYS"
        exit 1
    fi

    if [ "$key" == "quarantine_mode" ]; then
        case "$2" in
            auto|on|off) ;;
            *) echo -e "${RED}quarantine_mode must be: auto | on | off${NC}"; exit 1 ;;
        esac
    fi

    py "
import json,os,sys
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$CONFIG'))
except: d={}
key='$key'
val='$2'
bounds=$BOUNDS_PY
if key=='quarantine_mode':
    v=val
else:
    try: v=int(val)
    except: print('  ${RED}Invalid numeric value.${NC}'); sys.exit(1)
    if key in bounds:
        lo,hi=bounds[key]
        if not (lo<=v<=hi):
            print('  ${RED}Value out of allowed range (' + str(lo) + '-' + str(hi) + ') for ' + key + '.${NC}')
            sys.exit(1)
d[key]=v
json.dump(d,open('$CONFIG','w'),indent=2)
print('  ✅ Set $key =',v)
"
    if [ $? -ne 0 ]; then
        echo -e "${RED}Config পরিবর্তন ব্যর্থ — উপরের কারণে কিছু সংরক্ষিত হয়নি।${NC}"
        exit 1
    fi
    echo -e "${GREEN}✅ Config saved। পরবর্তী check cycle থেকেই কার্যকর হবে (restart লাগবে না)।${NC}"
}

# ── vg quarantine status/on/off/auto (trigger override) ─────────────────────

cmd_quarantine_status() {
    header; echo -e "\n  ${BOLD}Quarantine Status:${NC}\n"
    py "
import json
try: s=json.load(open('$STATE'))
except: s={}
try: c=json.load(open('$CONFIG'))
except: c={}
mode=c.get('quarantine_mode','auto')
active=s.get('quarantine_active',False)
print('  Mode      :',mode)
print('  Active    :', 'YES — strict per-IP thresholds কার্যকর' if active else 'no — normal thresholds কার্যকর')
print('  Last global rate:', s.get('last_cycle_total','-'))
"
    echo ""
}

cmd_quarantine_on() {
    py "
import json,os
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$CONFIG'))
except: d={}
d['quarantine_mode']='on'
json.dump(d,open('$CONFIG','w'),indent=2)
"
    echo -e "${RED}🚨 Quarantine মোড MANUAL ON। এখন strict per-IP threshold কার্যকর (quarantine_block_threshold/quarantine_perm_threshold)।${NC}"
    echo -e "${YELLOW}স্বাভাবিক অবস্থায় ফিরতে: vg quarantine-off  বা  vg quarantine-auto${NC}"
}

cmd_quarantine_off() {
    py "
import json,os
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$CONFIG'))
except: d={}
d['quarantine_mode']='off'
json.dump(d,open('$CONFIG','w'),indent=2)
"
    echo -e "${GREEN}✅ Quarantine মোড MANUAL OFF। Normal per-IP threshold কার্যকর হবে।${NC}"
}

cmd_quarantine_auto() {
    py "
import json,os
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$CONFIG'))
except: d={}
d['quarantine_mode']='auto'
json.dump(d,open('$CONFIG','w'),indent=2)
"
    echo -e "${GREEN}✅ Quarantine মোড AUTO তে ফিরিয়ে নেওয়া হলো (global rate অনুযায়ী নিজে নিজে on/off হবে)।${NC}"
}

# ── BLOCKLIST (normal + quarantine-triggered, একই ipset/JSON) ─────────────────

_show_blocklist() {
    local filter="$1"
    py "
import json,time
try: data=json.load(open('$BLOCKLIST'))
except: data={}
filt='$filter'
rows=[]
for ip,i in data.items():
    perm=i.get('permanent',False)
    label=i.get('label','')
    is_q='quarantine' in label
    if filt=='temp' and perm: continue
    if filt=='perm' and not perm: continue
    if filt=='quarantine' and not is_q: continue
    bt=time.strftime('%Y-%m-%d %H:%M',time.localtime(i.get('time',0)))
    if perm: ex='Never'
    else:
        exp=i.get('time',0)+(i.get('duration') or 0)
        ex=time.strftime('%Y-%m-%d %H:%M',time.localtime(exp))
    typ='PERMANENT' if perm else '7 Days'
    src='manual' if not i.get('auto') else ('quarantine' if is_q else 'auto')
    rows.append((ip,typ,bt,ex,src))
if not rows: print('  No entries.'); exit()
print(f\"  {'IP':<20} {'Type':<12} {'Blocked At':<18} {'Expires':<18} {'Source'}\")
print(f\"  {'─'*20} {'─'*12} {'─'*18} {'─'*18} {'─'*10}\")
for r in rows:
    print(f'  {r[0]:<20} {r[1]:<12} {r[2]:<18} {r[3]:<18} {r[4]}')
print()
print(f'  Total: {len(rows)}')
"
}

cmd_blocklist()            { header; echo -e "\n  ${BOLD}All Blocked IPs:${NC}\n"; _show_blocklist all; }
cmd_blocklist_temp()       { header; echo -e "\n  ${BOLD}Temp Blocked IPs (7-day):${NC}\n"; _show_blocklist temp; }
cmd_blocklist_perm()       { header; echo -e "\n  ${BOLD}Permanently Blocked IPs:${NC}\n"; _show_blocklist perm; }
cmd_blocklist_quarantine() { header; echo -e "\n  ${BOLD}Quarantine-triggered Blocks:${NC}\n"; _show_blocklist quarantine; }

_add_ips_to_blocklist() {
    local perm="$1"; shift
    local raw="$*"
    IFS=', ' read -ra ips <<< "$raw"
    local invalid=(); local added=()
    for ip in "${ips[@]}"; do
        ip=$(echo "$ip" | tr -d ',' | xargs)
        [ -z "$ip" ] && continue
        if ! valid_ip "$ip"; then invalid+=("$ip"); else added+=("$ip"); fi
    done
    [ ${#invalid[@]} -gt 0 ] && echo -e "${RED}Invalid IP(s): ${invalid[*]}${NC}"
    [ ${#added[@]} -eq 0 ] && echo -e "${YELLOW}No valid IPs to add.${NC}" && return

    ipset_batch_add "$IPSET_BLOCKLIST" "${added[@]}"
    py "
import json,time,os
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$BLOCKLIST'))
except: d={}
perm=$perm
for ip in '${added[*]}'.split():
    d[ip]={'time':time.time(),'duration':None if perm else 604800,'permanent':perm,'label':'PERMANENT' if perm else '7d','auto':False}
json.dump(d,open('$BLOCKLIST','w'),indent=2)
"
    for ip in "${added[@]}"; do echo -e "${GREEN}  ✅ Blocked: $ip${NC}"; done
}

cmd_blocklist_add()      { [ -z "$1" ] && echo -e "${RED}Usage: vg blocklist-add <ip> [ip2] ...${NC}" && exit 1; _add_ips_to_blocklist True "$@"; }
cmd_blocklist_add_temp() { [ -z "$1" ] && echo -e "${RED}Usage: vg blocklist-add-temp <ip> [ip2] ...${NC}" && exit 1; _add_ips_to_blocklist False "$@"; }

_remove_ips() {
    local raw="$*"
    IFS=', ' read -ra ips <<< "$raw"
    local invalid=(); local removed=()
    for ip in "${ips[@]}"; do
        ip=$(echo "$ip" | tr -d ',' | xargs)
        [ -z "$ip" ] && continue
        if ! valid_ip "$ip"; then invalid+=("$ip"); else removed+=("$ip"); fi
    done
    [ ${#invalid[@]} -gt 0 ] && echo -e "${RED}Invalid IP(s): ${invalid[*]}${NC}"
    [ ${#removed[@]} -eq 0 ] && return
    ipset_batch_del "$IPSET_BLOCKLIST" "${removed[@]}"
    py "
import json
try: d=json.load(open('$BLOCKLIST'))
except: d={}
for ip in '${removed[*]}'.split():
    d.pop(ip,None)
json.dump(d,open('$BLOCKLIST','w'),indent=2)
"
    for ip in "${removed[@]}"; do echo -e "${GREEN}  ✅ Removed: $ip${NC}"; done
}

cmd_blocklist_remove() { [ -z "$1" ] && echo -e "${RED}Usage: vg blocklist-remove <ip> [ip2]${NC}" && exit 1; _remove_ips "$@"; }

cmd_blocklist_remove_all() {
    echo -e "${YELLOW}Removing ALL blocked IPs...${NC}"
    count=$(py "
import json
try: data=json.load(open('$BLOCKLIST')); print(len(data))
except: print(0)
")
    ipset flush "$IPSET_BLOCKLIST" 2>/dev/null
    py "import json; json.dump({},open('$BLOCKLIST','w'),indent=2)"
    echo -e "${GREEN}✅ Done. ${count} IP(s) removed.${NC}"
}

cmd_blocklist_remove_all_temp() {
    echo -e "${YELLOW}Removing all temp (7-day) blocked IPs...${NC}"
    ips_to_del=$(py "
import json
try: data=json.load(open('$BLOCKLIST'))
except: data={}
print(' '.join(ip for ip,i in data.items() if not i.get('permanent')))
")
    IFS=' ' read -ra ips_arr <<< "$ips_to_del"
    [ ${#ips_arr[@]} -gt 0 ] && ipset_batch_del "$IPSET_BLOCKLIST" "${ips_arr[@]}"
    py "
import json
try: data=json.load(open('$BLOCKLIST'))
except: data={}
data={ip:i for ip,i in data.items() if i.get('permanent')}
json.dump(data,open('$BLOCKLIST','w'),indent=2)
"
    echo -e "${GREEN}✅ Done. ${#ips_arr[@]} IP(s) removed.${NC}"
}

cmd_blocklist_remove_all_perm() {
    echo -e "${YELLOW}Removing all permanently blocked IPs...${NC}"
    ips_to_del=$(py "
import json
try: data=json.load(open('$BLOCKLIST'))
except: data={}
print(' '.join(ip for ip,i in data.items() if i.get('permanent')))
")
    IFS=' ' read -ra ips_arr <<< "$ips_to_del"
    [ ${#ips_arr[@]} -gt 0 ] && ipset_batch_del "$IPSET_BLOCKLIST" "${ips_arr[@]}"
    py "
import json
try: data=json.load(open('$BLOCKLIST'))
except: data={}
data={ip:i for ip,i in data.items() if not i.get('permanent')}
json.dump(data,open('$BLOCKLIST','w'),indent=2)
"
    echo -e "${GREEN}✅ Done. ${#ips_arr[@]} IP(s) removed.${NC}"
}

# ── WHITELIST ─────────────────────────────────────────────────────────────────

cmd_whitelist() {
    header; echo -e "\n  ${BOLD}Whitelisted IPs:${NC}\n"
    py "
import json,time
sys_ips={'127.0.0.1':{'added':0,'note':'system'},'::1':{'added':0,'note':'system'}}
try: u=json.load(open('$WHITELIST')); sys_ips.update(u)
except: pass
if not sys_ips: print('  No entries.'); exit()
print(f\"  {'IP':<22} {'Added':<20} {'Note'}\")
print(f\"  {'─'*22} {'─'*20} {'─'*20}\")
for ip,i in sys_ips.items():
    added=time.strftime('%Y-%m-%d %H:%M',time.localtime(i.get('added',0))) if i.get('added') else 'system'
    print(f\"  {ip:<22} {added:<20} {i.get('note','')}\")
print()
"
}

_add_ips_to_whitelist() {
    local raw="$*"
    IFS=', ' read -ra ips <<< "$raw"
    local invalid=(); local added=()
    for ip in "${ips[@]}"; do
        ip=$(echo "$ip" | tr -d ',' | xargs)
        [ -z "$ip" ] && continue
        if ! valid_ip "$ip"; then invalid+=("$ip"); else added+=("$ip"); fi
    done
    [ ${#invalid[@]} -gt 0 ] && echo -e "${RED}Invalid IP(s): ${invalid[*]}${NC}"
    [ ${#added[@]} -eq 0 ] && echo -e "${YELLOW}No valid IPs to add.${NC}" && return
    py "
import json,time,os
os.makedirs('$BASE',exist_ok=True)
try: d=json.load(open('$WHITELIST'))
except: d={}
for ip in '${added[*]}'.split():
    d[ip]={'added':time.time(),'note':'manual'}
json.dump(d,open('$WHITELIST','w'),indent=2)
"
    ipset_batch_del "$IPSET_BLOCKLIST" "${added[@]}"
    py "
import json
try: bl=json.load(open('$BLOCKLIST'))
except: bl={}
for ip in '${added[*]}'.split():
    bl.pop(ip,None)
json.dump(bl,open('$BLOCKLIST','w'),indent=2)
"
    for ip in "${added[@]}"; do echo -e "${GREEN}  ✅ Whitelisted: $ip${NC}"; done
}

_remove_ips_from_whitelist() {
    local raw="$*"
    IFS=', ' read -ra ips <<< "$raw"
    local invalid=()
    for ip in "${ips[@]}"; do
        ip=$(echo "$ip" | tr -d ',' | xargs)
        [ -z "$ip" ] && continue
        if ! valid_ip "$ip"; then
            invalid+=("$ip")
        else
            python3 -c "
import json
try: d=json.load(open('$WHITELIST')); d.pop('$ip',None); json.dump(d,open('$WHITELIST','w'),indent=2)
except: pass
"
            echo -e "${GREEN}  ✅ Removed: $ip${NC}"
        fi
    done
    [ ${#invalid[@]} -gt 0 ] && echo -e "${RED}Invalid IP(s): ${invalid[*]}${NC}"
}

cmd_whitelist_add()        { [ -z "$1" ] && echo -e "${RED}Usage: vg whitelist-add <ip> [ip2]${NC}" && exit 1; _add_ips_to_whitelist "$@"; }
cmd_whitelist_remove()     { [ -z "$1" ] && echo -e "${RED}Usage: vg whitelist-remove <ip> [ip2]${NC}" && exit 1; _remove_ips_from_whitelist "$@"; }
cmd_whitelist_remove_all() {
    py "import json; json.dump({},open('$WHITELIST','w'),indent=2); print('  Whitelist cleared.')"
    echo -e "${GREEN}✅ Done.${NC}"
}

# ── LOG ───────────────────────────────────────────────────────────────────────

cmd_log()       { echo -e "${CYAN}━━━━ Live Log (Ctrl+C to exit) ━━━━${NC}"; tail -f "$LOGFILE"; }
cmd_log_clear() { > "$LOGFILE"; echo -e "${GREEN}✅ Log cleared.${NC}"; }

# ── SERVICE ───────────────────────────────────────────────────────────────────

cmd_start()   { systemctl start   ddos-guard && echo -e "${GREEN}▶ Started.${NC}"; }
cmd_stop()    { systemctl stop    ddos-guard && echo -e "${YELLOW}⏹ Stopped.${NC}"; }
cmd_restart() { systemctl restart ddos-guard && echo -e "${GREEN}↺ Restarted.${NC}"; }

# ── HELP ──────────────────────────────────────────────────────────────────────

cmd_help() {
    header; echo ""
    echo -e "  ${BOLD}INFO${NC}"
    echo -e "  vg status                      Service + quarantine + threshold সারমর্ম"
    echo -e "  vg log                         Live log"
    echo -e "  vg log-clear                   Clear log file"
    echo ""
    echo -e "  ${BOLD}CONFIG${NC}"
    echo -e "  vg config                      Show সব config"
    echo -e "  vg config <key> <value>        Edit config (live, no restart needed)"
    echo ""
    echo -e "  ${BOLD}QUARANTINE (manual trigger override)${NC}"
    echo -e "  vg quarantine-status           বর্তমান quarantine অবস্থা"
    echo -e "  vg quarantine-on               Manually quarantine ON (strict thresholds কার্যকর হবে)"
    echo -e "  vg quarantine-off              Manually quarantine OFF (normal thresholds কার্যকর হবে)"
    echo -e "  vg quarantine-auto             Auto-detection মোডে ফিরিয়ে নিন"
    echo ""
    echo -e "  ${BOLD}BLOCKLIST (normal + quarantine-triggered, একই list)${NC}"
    echo -e "  vg blocklist                   Show all blocked IPs"
    echo -e "  vg blocklist-temp              Show 7-day blocked only"
    echo -e "  vg blocklist-perm              Show permanent blocked only"
    echo -e "  vg blocklist-quarantine        শুধু quarantine চলাকালীন blocked IP দেখুন"
    echo -e "  vg blocklist-add <ip> [ip2]    Add IP(s) — permanent"
    echo -e "  vg blocklist-add-temp <ip>     Add IP(s) — 7 days"
    echo -e "  vg blocklist-remove <ip> [ip2] Remove specific IP(s)"
    echo -e "  vg blocklist-remove-all        Remove ALL blocked IPs"
    echo -e "  vg blocklist-remove-all-temp   Remove all 7-day blocks"
    echo -e "  vg blocklist-remove-all-perm   Remove all permanent blocks"
    echo ""
    echo -e "  ${BOLD}WHITELIST${NC}"
    echo -e "  vg whitelist                   Show whitelisted IPs"
    echo -e "  vg whitelist-add <ip> [ip2]    Add IP(s)"
    echo -e "  vg whitelist-remove <ip> [ip2] Remove IP(s)"
    echo -e "  vg whitelist-remove-all        Remove all"
    echo ""
    echo -e "  ${BOLD}SERVICE${NC}"
    echo -e "  vg start / vg stop / vg restart"
    echo ""
}

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

case "$1" in
    status)                    cmd_status ;;
    config)                    cmd_config "$2" "$3" ;;
    log)                       cmd_log ;;
    log-clear)                 cmd_log_clear ;;

    quarantine-status)         cmd_quarantine_status ;;
    quarantine-on)             cmd_quarantine_on ;;
    quarantine-off)            cmd_quarantine_off ;;
    quarantine-auto)           cmd_quarantine_auto ;;

    blocklist)                 cmd_blocklist ;;
    blocklist-temp)            cmd_blocklist_temp ;;
    blocklist-perm)            cmd_blocklist_perm ;;
    blocklist-quarantine)      cmd_blocklist_quarantine ;;
    blocklist-add)             shift; cmd_blocklist_add "$@" ;;
    blocklist-add-temp)        shift; cmd_blocklist_add_temp "$@" ;;
    blocklist-remove)          shift; cmd_blocklist_remove "$@" ;;
    blocklist-remove-all)      cmd_blocklist_remove_all ;;
    blocklist-remove-all-temp) cmd_blocklist_remove_all_temp ;;
    blocklist-remove-all-perm) cmd_blocklist_remove_all_perm ;;

    whitelist)                 cmd_whitelist ;;
    whitelist-add)             shift; cmd_whitelist_add "$@" ;;
    whitelist-remove)          shift; cmd_whitelist_remove "$@" ;;
    whitelist-remove-all)      cmd_whitelist_remove_all ;;

    start)                     cmd_start ;;
    stop)                      cmd_stop ;;
    restart)                   cmd_restart ;;
    help|--help|-h)            cmd_help ;;
    *)                         cmd_help ;;
esac
