#!/bin/bash
# RTExit — Master Tool Verification Script
# Usage:
#   bash rt-verify-all.sh           → full verbose report
#   bash rt-verify-all.sh --quick   → phase summary only
#   bash rt-verify-all.sh --phase 3 → single phase

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

QUICK=0; SINGLE_PHASE=0

while [[ $# -gt 0 ]]; do
  case $1 in
    --quick) QUICK=1; shift ;;
    --phase) SINGLE_PHASE=$2; shift 2 ;;
    *) shift ;;
  esac
done

# Strip ANSI codes helper
strip_ansi() { sed 's/\x1b\[[0-9;]*m//g; s/\x1b\[[0-9]*[A-Za-z]//g'; }

# Banner
clear
printf "${RED}"
cat << 'EOF'
  ██████╗ ████████╗███████╗██╗  ██╗██╗████████╗
  ██╔══██╗╚══██╔══╝██╔════╝╚██╗██╔╝██║╚══██╔══╝
  ██████╔╝   ██║   █████╗   ╚███╔╝ ██║   ██║
  ██╔══██╗   ██║   ██╔══╝   ██╔██╗ ██║   ██║
  ██║  ██║   ██║   ███████╗██╔╝ ██╗██║   ██║
  ╚═╝  ╚═╝   ╚═╝   ╚══════╝╚═╝  ╚═╝╚═╝   ╚═╝
EOF
printf "${NC}"
printf "${BOLD}  RTExit Full Tool Verification — 300+ Tools${NC}\n"
printf "  $(date '+%Y-%m-%d %H:%M:%S')\n\n"

PHASES=(
  "1:phase1-scanning.sh:Scanning & Recon"
  "2:phase2-web.sh:Web Application Testing"
  "3:phase3-ad.sh:Active Directory & Windows"
  "4:phase4-cloud.sh:Cloud Platforms"
  "5:phase5-mobile.sh:Mobile Testing"
  "6:phase6-c2.sh:C2 & Post-Exploitation"
  "7:phase7-osint.sh:OSINT & Intelligence"
  "8:phase8-creds.sh:Passwords & Credentials"
  "9:phase9-binary.sh:Binary Analysis & RE"
  "10:phase10-network.sh:Network & WiFi"
  "11:phase11-specialist.sh:Specialist"
)

GRAND_PASS=0; GRAND_FAIL=0; GRAND_WARN=0; GRAND_TOTAL=0
declare -a SUMMARY=()
declare -a ALL_MISSING=()

for entry in "${PHASES[@]}"; do
  NUM=$(echo "$entry" | cut -d: -f1)
  SCRIPT=$(echo "$entry" | cut -d: -f2)
  NAME=$(echo "$entry" | cut -d: -f3)

  [ "$SINGLE_PHASE" -ne 0 ] && [ "$NUM" -ne "$SINGLE_PHASE" ] && continue

  SCRIPT_PATH="$SCRIPT_DIR/$SCRIPT"
  [ ! -f "$SCRIPT_PATH" ] && continue

  # Run phase and capture output
  OUTPUT=$(bash "$SCRIPT_PATH" 2>/dev/null)
  CLEAN=$(echo "$OUTPUT" | strip_ansi)

  # Count results
  P=$(echo "$CLEAN" | grep -c '✅' 2>/dev/null || echo 0)
  F=$(echo "$CLEAN" | grep -c '❌' 2>/dev/null || echo 0)
  W=$(echo "$CLEAN" | grep -c '⚠️' 2>/dev/null || echo 0)
  T=$((P + F))
  PCT=0; [ "$T" -gt 0 ] && PCT=$((P * 100 / T))

  # Collect missing tool names
  while IFS= read -r line; do
    TOOL=$(echo "$line" | grep '❌' | awk '{print $2}' | head -1)
    [ -n "$TOOL" ] && ALL_MISSING+=("Phase${NUM}/${NAME}: ${TOOL}")
  done <<< "$CLEAN"

  GRAND_PASS=$((GRAND_PASS + P))
  GRAND_FAIL=$((GRAND_FAIL + F))
  GRAND_WARN=$((GRAND_WARN + W))
  GRAND_TOTAL=$((GRAND_TOTAL + T))

  # Store for summary
  SUMMARY+=("$NUM:$NAME:$P:$F:$T:$PCT")

  # Print full output if not quick
  if [ "$QUICK" -eq 0 ]; then
    echo "$OUTPUT"
    echo ""
  else
    # Quick mode — one line per phase
    if   [ "$PCT" -ge 90 ]; then COLOR="${GREEN}"
    elif [ "$PCT" -ge 70 ]; then COLOR="${YELLOW}"
    else COLOR="${RED}"; fi

    printf "  Phase %2d │ %-32s │ ${GREEN}%3d✅${NC} ${RED}%3d❌${NC} │ %b%3d%%${NC}\n" \
      "$NUM" "$NAME" "$P" "$F" "$COLOR" "$PCT"
  fi
done

# ── Summary Table ─────────────────────────────────────────────────────────────
echo ""
printf "${CYAN}${BOLD}┌──────────────────────────────────────────────────────────────┐${NC}\n"
printf "${CYAN}${BOLD}│                   VERIFICATION SUMMARY                      │${NC}\n"
printf "${CYAN}${BOLD}├────┬──────────────────────────────────┬──────┬──────┬───────┤${NC}\n"
printf "${CYAN}${BOLD}│ Ph │ Phase Name                       │  ✅  │  ❌  │   %%  │${NC}\n"
printf "${CYAN}${BOLD}├────┼──────────────────────────────────┼──────┼──────┼───────┤${NC}\n"

for entry in "${SUMMARY[@]}"; do
  NUM=$(echo "$entry" | cut -d: -f1)
  NAME=$(echo "$entry" | cut -d: -f2)
  P=$(echo "$entry" | cut -d: -f3)
  F=$(echo "$entry" | cut -d: -f4)
  T=$(echo "$entry" | cut -d: -f5)
  PCT=$(echo "$entry" | cut -d: -f6)

  if   [ "$PCT" -ge 90 ]; then PCOL="${GREEN}"
  elif [ "$PCT" -ge 70 ]; then PCOL="${YELLOW}"
  else PCOL="${RED}"; fi

  printf "│ ${BOLD}%2d${NC} │ %-32s │ ${GREEN}%4d${NC} │ ${RED}%4d${NC} │ %b%5d%%${NC} │\n" \
    "$NUM" "$NAME" "$P" "$F" "$PCOL" "$PCT"
done

printf "${CYAN}${BOLD}├────┴──────────────────────────────────┴──────┴──────┴───────┤${NC}\n"

GRAND_PCT=0; [ "$GRAND_TOTAL" -gt 0 ] && GRAND_PCT=$((GRAND_PASS * 100 / GRAND_TOTAL))
if   [ "$GRAND_PCT" -ge 90 ]; then GCOL="${GREEN}"
elif [ "$GRAND_PCT" -ge 70 ]; then GCOL="${YELLOW}"
else GCOL="${RED}"; fi

printf "${CYAN}${BOLD}│${NC} ${BOLD}TOTAL${NC}                                    ${GREEN}${BOLD}%4d${NC}   ${RED}${BOLD}%4d${NC}   %b${BOLD}%4d%%${NC}  ${CYAN}${BOLD}│${NC}\n" \
  "$GRAND_PASS" "$GRAND_FAIL" "$GCOL" "$GRAND_PCT"
printf "${CYAN}${BOLD}└──────────────────────────────────────────────────────────────┘${NC}\n"

# ── Progress Bar ──────────────────────────────────────────────────────────────
echo ""
printf "  "
BAR=50; FILLED=$((GRAND_PCT * BAR / 100))
printf "${BOLD}[${NC}"
for ((i=0; i<BAR; i++)); do
  [ $i -lt $FILLED ] && printf "${GCOL}█${NC}" || printf "${GRAY}░${NC}"
done
printf "${BOLD}]${NC} %b${BOLD} %d%%${NC}  (%d / %d tools)\n" "$GCOL" "$GRAND_PCT" "$GRAND_PASS" "$GRAND_TOTAL"

# ── Missing Tools ─────────────────────────────────────────────────────────────
if [ "${#ALL_MISSING[@]}" -gt 0 ]; then
  echo ""
  printf "${RED}${BOLD}  ❌ Missing Tools:${NC}\n"
  for m in "${ALL_MISSING[@]}"; do
    printf "     ${RED}•${NC} %s\n" "$m"
  done
fi

# ── Verdict ───────────────────────────────────────────────────────────────────
echo ""
if   [ "$GRAND_PCT" -ge 95 ]; then
  printf "  ${GREEN}${BOLD}🔥 ELITE — Full APT-level toolkit. Ready for any engagement.${NC}\n"
elif [ "$GRAND_PCT" -ge 85 ]; then
  printf "  ${GREEN}${BOLD}✅ PROFESSIONAL — Ready for most engagements.${NC}\n"
elif [ "$GRAND_PCT" -ge 70 ]; then
  printf "  ${YELLOW}${BOLD}⚠️  OPERATIONAL — Install missing tools before engagement.${NC}\n"
else
  printf "  ${RED}${BOLD}❌ INCOMPLETE — Run: bash /opt/rtexit/scripts/rt-native-install.sh${NC}\n"
fi
echo ""
