#!/usr/bin/env bash
set -euo pipefail

# Script Name: bb-recon
# Description: Bug-bounty-safe web application reconnaissance
# Usage: bb-recon <url>
# Creates tmux window with parallel safe recon (nuclei info/low, katana, subdomain takeover)
# Based on Jason Haddix's Bug Hunter Methodology

VERSION="1.0.0"

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

# Status indicators
readonly GREENPLUS="${GREEN}[+]${NC}"
readonly GREENSTAR="${YELLOW}[*]${NC}"
readonly REDMINUS="${RED}[-]${NC}"
readonly REDEXCLAIM="${RED}[!]${NC}"

show_help() {
  echo -e "${BOLD}bb-recon${NC} - Bug Bounty Reconnaissance v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  bb-recon <url>"
  echo
  echo -e "${BOLD}DESCRIPTION:${NC}"
  echo "  Bug-bounty-safe web reconnaissance with 4 parallel panes:"
  echo "  - Pane 1 (top-left):     Nuclei (info/low + subdomain takeover)"
  echo "  - Pane 2 (top-right):    httpx (technology detection + security headers)"
  echo "  - Pane 3 (bottom-left):  Katana (JS-aware crawler for endpoint discovery)"
  echo "  - Pane 4 (bottom-right): Live results dashboard"
  echo
  echo -e "${BOLD}BUG BOUNTY PHILOSOPHY:${NC}"
  echo "  Based on Jason Haddix's Bug Hunter Methodology:"
  echo "  - Find FEATURES first, bugs second"
  echo "  - Focus on interactive, dynamic applications"
  echo "  - Conservative tools only (no exploitation)"
  echo "  - Discovery over brute-forcing"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  bb-recon https://target.com"
  echo "  bb-recon https://bugcrowd-target.com"
  echo "  bb-recon https://h1-program.hackerone.net"
  echo
  echo -e "${BOLD}OUTPUT:${NC}"
  echo "  All results saved to: ./bb-recon-<target>-<timestamp>/"
  echo
  echo -e "${BOLD}SAFE FOR BUG BOUNTY:${NC}"
  echo "  ✓ No directory brute-forcing (Feroxbuster removed)"
  echo "  ✓ No parameter fuzzing (Arjun removed)"
  echo "  ✓ Info/Low severity only (no exploit templates)"
  echo "  ✓ JS analysis for endpoint discovery (passive)"
  echo "  ✓ Subdomain takeover checks (safe)"
}

# Check required tools
check_tools() {
  local missing=()
  local optional_missing=()

  # Core tools
  command -v tmux &>/dev/null || missing+=("tmux")

  # Bug bounty tools (all optional but recommended)
  command -v nuclei &>/dev/null || optional_missing+=("nuclei")
  command -v katana &>/dev/null || optional_missing+=("katana")
  command -v httpx &>/dev/null || optional_missing+=("httpx")

  if [[ ${#missing[@]} -gt 0 ]]; then
    echo -e "${RED}Error:${NC} Missing required tools: ${missing[*]}"
    exit 1
  fi

  if [[ ${#optional_missing[@]} -gt 0 ]]; then
    echo -e "${YELLOW}⚠${NC} Optional tools missing (scans will be skipped): ${optional_missing[*]}"
    echo -e "${CYAN}Install with:${NC}"
    for tool in "${optional_missing[@]}"; do
      case "$tool" in
        nuclei)   echo "  go install -v github.com/projectdiscovery/nuclei/v3/cmd/nuclei@latest" ;;
        katana)   echo "  go install github.com/projectdiscovery/katana/cmd/katana@latest" ;;
        httpx)    echo "  go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest" ;;
      esac
    done
    echo
  fi
}

# Create output directory
setup_output_dir() {
  local url="$1"
  local timestamp=$(date +%Y%m%d-%H%M%S)
  local clean_url=$(echo "$url" | tr '/:' '_' | tr -d 'http')

  OUTPUT_DIR="bb-recon-${clean_url}-${timestamp}"
  mkdir -p "$OUTPUT_DIR"

  echo -e "${GREEN}✓${NC} Output directory: ${BOLD}$OUTPUT_DIR${NC}"
}

# Main bug bounty recon function
run_bb_recon() {
  local url="$1"

  # Ensure URL has http:// or https://
  if [[ ! "$url" =~ ^https?:// ]]; then
    url="https://$url"
    echo -e "${YELLOW}⚠${NC} No protocol specified, using HTTPS: $url"
  fi

  echo -e "${CYAN}${BOLD}"
  echo "╔════════════════════════════════════════════════════════════╗"
  echo "║        Bug Bounty Reconnaissance (Safe Mode)               ║"
  echo "║                Target: $url"
  echo "║        Based on: Jason Haddix's Methodology                ║"
  echo "╚════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"

  # Create output directory
  setup_output_dir "$url"

  # Check if in tmux
  if [[ -z "${TMUX:-}" ]]; then
    echo -e "${YELLOW}⚠${NC} Not in tmux session - running sequentially"
    run_scans_sequential "$url"
    return
  fi

  # Create tmux window
  WINDOW_NAME="--> BB: ${url:0:20}... <--"
  tmux new-window -n "$WINDOW_NAME"

  # Split into 4 panes with explicit targeting
  # Layout: 2x2 grid with pipelines and live monitoring
  # ACTUAL pane numbers after splits: 1, 2, 3, 4 (no pane 0!)
  #   [1: nuclei]              [2: feroxbuster → arjun]
  #   [3: katana]              [4: live dashboard]

  # Create 2x2 grid layout
  # CRITICAL: Tmux pane numbering behavior discovered through testing:
  #   Step 1: split-window -h creates [0:left] [1:right]
  #   Step 2: select pane 0, split-window -v creates [0:TL] [1:BL] [2:right]
  #   Step 3: select pane 2, split-window -v creates [1:TL] [2:TR] [3:BL] [4:BR]
  #
  #   PANE 0 DISAPPEARS during this process! Final panes are numbered 1, 2, 3, 4

  # Split horizontally first (left | right)
  tmux split-window -h

  # Split left column vertically
  tmux select-pane -t 0
  tmux split-window -v

  # Split right column vertically (target pane 2 after left split)
  tmux select-pane -t 2
  tmux split-window -v

  # Force tiled layout for perfect 2x2 grid (equal-sized panes)
  tmux select-layout tiled

  # Final verified pane layout after tmux renumbering and tiled layout:
  #   1 (top-left)    2 (top-right)
  #   3 (bottom-left) 4 (bottom-right)

  # Send commands to each pane with ACTUAL pane numbers after splits
  # After all splits complete, tmux renumbers panes as: 1 (TL), 2 (TR), 3 (BL), 4 (BR)
  # (pane 0 disappears during the splitting process)

  # Pane 1 (top-left): Nuclei (info/low severity + subdomain takeover)
  tmux select-pane -t 1
  if command -v nuclei &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting Nuclei scan (info/low + subdomain takeover)...${NC}' && nuclei -u '$url' -s info,low -t exposed-panels/ -t exposures/ -t misconfiguration/ -t technologies/ -t takeovers/ -t subdomain-takeover/ -o nuclei.txt 2>&1 | tee nuclei.log && echo -e '${GREEN}✓ Nuclei complete${NC}'" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ nuclei not installed - skipping${NC}'" C-m
  fi

  # Pane 2 (top-right): httpx technology detection and security headers
  tmux select-pane -t 2
  if command -v httpx &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Technology detection with httpx...${NC}' && echo '$url' | httpx -td -title -status-code -content-length -server -tech-detect -follow-redirects -o httpx.txt && echo -e '${GREEN}✓ httpx complete${NC}'" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ httpx not installed - skipping tech detection${NC}'" C-m
  fi

  # Pane 3 (bottom-left): katana (web crawler with all output formats)
  tmux select-pane -t 3
  if command -v katana &>/dev/null; then
    # Full katana with all output formats as originally requested
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting katana crawler (full output)...${NC}' && katana -u '$url' -jc -kf all -aff -d 10 -o katana.txt 2>&1 | tee katana.log && katana -u '$url' -jc -kf all -aff -d 10 -f path -o katana_paths.txt && katana -u '$url' -jc -kf all -aff -d 10 -f url -o katana_urls.txt && katana -u '$url' -jc -kf all -aff -d 10 -f udir -o katana_dirs.txt && cat katana_dirs.txt 2>/dev/null | sort -u >> urls.txt && cat katana_paths.txt 2>/dev/null | sed 's/^.//g' >> paths.txt && echo -e '${GREEN}✓ Katana complete (all formats)${NC}'" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ katana not installed - skipping${NC}'" C-m
  fi

  # Pane 4 (bottom-right): Live results dashboard
  tmux select-pane -t 4
  # Watch output files and show live statistics
  tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${CYAN}╔══════════════════════════════════════════════╗${NC}' && echo -e '${CYAN}║    BUG BOUNTY RECON DASHBOARD (SAFE MODE)   ║${NC}' && echo -e '${CYAN}╚══════════════════════════════════════════════╝${NC}' && echo -e '${YELLOW}[*] Monitoring output files...${NC}' && while true; do clear; echo -e '${CYAN}═══ Bug Bounty Safe Reconnaissance ═══${NC}'; echo; echo -e '${GREEN}Nuclei (info/low + takeover):${NC}'; [ -f nuclei.txt ] && [ -s nuclei.txt ] && echo \"  Found: \$(wc -l < nuclei.txt 2>/dev/null || echo 0) findings\" || [ -f nuclei.log ] && grep -q 'complete' nuclei.log 2>/dev/null && echo '  Complete (0 findings)' || echo '  Waiting...'; echo; echo -e '${GREEN}Technology Stack (httpx):${NC}'; [ -f httpx.txt ] && [ -s httpx.txt ] && echo \"  Detected: \$(grep -c 'http' httpx.txt 2>/dev/null || echo 0) technologies\" || echo '  Waiting...'; echo; echo -e '${GREEN}Katana Crawler:${NC}'; [ -f katana.txt ] && [ -s katana.txt ] && echo \"  Crawled: \$(wc -l < katana.txt 2>/dev/null || echo 0) URLs\" || echo '  Waiting...'; echo; echo -e '${GREEN}JS Endpoints:${NC}'; [ -f katana_paths.txt ] && [ -s katana_paths.txt ] && echo \"  Discovered: \$(wc -l < katana_paths.txt 2>/dev/null || echo 0) paths\" || echo '  None yet'; echo; echo -e '${CYAN}Latest Discoveries:${NC}'; [ -f katana_urls.txt ] && tail -5 katana_urls.txt 2>/dev/null || echo '  None yet'; echo; echo -e '${YELLOW}[Press Ctrl+C to stop monitoring]${NC}'; sleep 3; done" C-m

  # Focus back on top-left pane (nuclei)
  tmux select-pane -t 1

  echo
  echo -e "${GREEN}✓${NC} Tmux bug bounty recon window created"
  echo -e "${CYAN}[*]${NC} Switch to window: ${BOLD}--> BB: ${url:0:20}... <--${NC}"
  echo -e "${CYAN}[*]${NC} Results will be in: ${BOLD}$OUTPUT_DIR${NC}"
  echo
  echo -e "${GREEN}Bug Bounty Safe:${NC}"
  echo -e "  ✓ No directory brute-forcing"
  echo -e "  ✓ No parameter fuzzing"
  echo -e "  ✓ Info/Low severity only"
  echo -e "  ✓ Passive endpoint discovery"
}

# Sequential execution (when not in tmux)
run_scans_sequential() {
  local url="$1"

  cd "$OUTPUT_DIR"

  echo -e "\n${GREENSTAR} Running nuclei (info/low + subdomain takeover)...${NC}"
  command -v nuclei &>/dev/null && nuclei -u "$url" -s info,low -t exposed-panels/ -t exposures/ -t misconfiguration/ -t technologies/ -t takeovers/ -t subdomain-takeover/ -o nuclei.txt || echo "nuclei not installed"

  echo -e "\n${GREENSTAR} Technology detection with httpx...${NC}"
  command -v httpx &>/dev/null && echo "$url" | httpx -td -title -status-code -content-length -server -tech-detect -follow-redirects -o httpx.txt || echo "httpx not installed"

  echo -e "\n${GREENSTAR} Running katana (JS-aware crawler)...${NC}"
  if command -v katana &>/dev/null; then
    katana -u "$url" -jc -kf all -aff -d 10 -o katana.txt
    katana -u "$url" -jc -kf all -aff -d 10 -f path -o katana_paths.txt
    katana -u "$url" -jc -kf all -aff -d 10 -f url -o katana_urls.txt
  fi

  cd ..

  echo -e "\n${GREEN}✓${NC} Bug bounty recon complete! Results in: ${BOLD}$OUTPUT_DIR${NC}"
}

# Parse arguments
if [[ $# -eq 0 ]] || [[ "$1" =~ ^(-h|--help|help)$ ]]; then
  show_help
  exit 0
fi

url="$1"

# Validate URL
if [[ -z "$url" ]]; then
  echo -e "${RED}Error:${NC} URL required"
  echo "Usage: bb-recon <url>"
  exit 1
fi

# Check tools
check_tools

# Run bug bounty reconnaissance
run_bb_recon "$url"
