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

# Script Name: light-recon
# Description: Light web reconnaissance (browser-like, low detectability)
# Usage: light-recon <url>
# Tier 2: Between passive and active - mimics normal browsing

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}light-recon${NC} - Light Web Reconnaissance v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  light-recon <url>"
  echo
  echo -e "${BOLD}DESCRIPTION:${NC}"
  echo "  Browser-like reconnaissance with low detectability"
  echo "  Creates tmux window with 3 panes:"
  echo "  - Pane 1 (left):   httpx (HTTP probing with tech detection)"
  echo "  - Pane 2 (top-right): gowitness (visual screenshots)"
  echo "  - Pane 3 (bottom-right): results dashboard"
  echo
  echo -e "${BOLD}WHAT IS LIGHT RECON?${NC}"
  echo "  ✓ HTTP/HTTPS probing (looks like normal browser request)"
  echo "  ✓ Screenshot capture (headless browser)"
  echo "  ✓ Technology fingerprinting (Wappalyzer-style)"
  echo "  ✓ Security headers analysis"
  echo "  ✓ SSL/TLS information"
  echo "  ✓ Redirect chain following"
  echo
  echo "  ✗ No directory brute-forcing"
  echo "  ✗ No vulnerability scanning"
  echo "  ✗ No aggressive crawling"
  echo
  echo -e "${BOLD}EXAMPLES:${NC}"
  echo "  light-recon http://target.htb"
  echo "  light-recon https://example.com"
  echo "  light-recon 10.10.10.5"
  echo
  echo -e "${BOLD}OUTPUT:${NC}"
  echo "  All results saved to: ./light-recon-<target>-<timestamp>/"
  echo
  echo -e "${BOLD}DETECTABILITY:${NC}"
  echo "  🟡 Low - Appears as normal browser traffic"
  echo "  Safe for bug bounty initial recon phase"
  echo "  Use before aggressive scanning (web-recon)"
}

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

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

  # Light recon tools (all optional but warn)
  command -v httpx &>/dev/null || optional_missing+=("httpx")
  command -v gowitness &>/dev/null || optional_missing+=("gowitness")

  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
        httpx)      echo "  go install -v github.com/projectdiscovery/httpx/cmd/httpx@latest" ;;
        gowitness)  echo "  go install github.com/sensepost/gowitness@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="light-recon-${clean_url}-${timestamp}"
  mkdir -p "$OUTPUT_DIR"
  mkdir -p "$OUTPUT_DIR/screenshots"

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

# Main light-recon function
run_light_recon() {
  local url="$1"

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

  echo -e "${CYAN}${BOLD}"
  echo "╔════════════════════════════════════════════════════════════╗"
  echo "║       Light Web Reconnaissance (Browser-Like)             ║"
  echo "║                Target: $url"
  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 with 3 panes
  WINDOW_NAME="--> Light: ${url:0:20}... <--"
  tmux new-window -n "$WINDOW_NAME"

  # Create layout: [Left wide] [Right split top/bottom]
  # With 3 panes, tmux uses different numbering than 4-pane layouts
  # After splits: [0: left-wide] [1: top-right] [2: bottom-right]

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

  # Split right pane vertically
  tmux select-pane -t 1
  tmux split-window -v

  # Resize left pane to be wider (60/40 split)
  tmux select-pane -t 0
  tmux resize-pane -R 30

  # Final 3-pane layout:
  #   0 (left-wide)    1 (top-right)
  #                    2 (bottom-right)

  # Pane 0 (left): httpx - comprehensive HTTP probing
  tmux select-pane -t 0
  if command -v httpx &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting httpx HTTP probing...${NC}' && echo '$url' | httpx -silent -title -tech-detect -status-code -content-length -web-server -method -ip -cname -cdn -follow-redirects -tls-probe -pipeline -json -o httpx-detailed.json 2>&1 | tee httpx.log && echo '$url' | httpx -silent -sc -title -tech-detect -web-server -ip -location -cdn -o httpx-summary.txt && echo -e '${GREEN}✓ httpx complete${NC}' && echo && echo -e '${CYAN}Summary:${NC}' && cat httpx-summary.txt" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ httpx not installed - skipping${NC}'" C-m
  fi

  # Pane 1 (top-right): gowitness - screenshot capture
  tmux select-pane -t 1
  if command -v gowitness &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting gowitness screenshot capture...${NC}' && gowitness single '$url' --screenshot-path=./screenshots/ --disable-logging --timeout 30 2>&1 | tee gowitness.log && echo -e '${GREEN}✓ gowitness complete${NC}' && echo && ls -lh screenshots/ | tail -5" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ gowitness not installed - skipping${NC}'" C-m
  fi

  # Pane 2 (bottom-right): Live results dashboard
  tmux select-pane -t 2
  tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${CYAN}╔══════════════════════════════════════════════╗${NC}' && echo -e '${CYAN}║       LIGHT RECON RESULTS DASHBOARD          ║${NC}' && echo -e '${CYAN}╚══════════════════════════════════════════════╝${NC}' && echo -e '${YELLOW}[*] Monitoring output files...${NC}' && while true; do clear; echo -e '${CYAN}═══ Scan Progress ═══${NC}'; echo; echo -e '${GREEN}HTTP Probing (httpx):${NC}'; [ -f httpx-summary.txt ] && [ -s httpx-summary.txt ] && cat httpx-summary.txt || echo '  Waiting...'; echo; echo -e '${GREEN}Screenshots (gowitness):${NC}'; [ -d screenshots ] && SCREENSHOT_COUNT=\$(ls -1 screenshots/*.png 2>/dev/null | wc -l) && echo \"  Captured: \$SCREENSHOT_COUNT screenshot(s)\" && ls -1 screenshots/*.png 2>/dev/null | head -3 || echo '  Waiting...'; echo; echo -e '${GREEN}Technology Detection:${NC}'; [ -f httpx-detailed.json ] && [ -s httpx-detailed.json ] && jq -r '.tech[]' httpx-detailed.json 2>/dev/null | sort -u | sed 's/^/  - /' | head -10 || echo '  Waiting...'; echo; echo -e '${YELLOW}[Press Ctrl+C to stop monitoring]${NC}'; sleep 5; done" C-m

  # Focus back on httpx pane
  tmux select-pane -t 0

  echo
  echo -e "${GREEN}✓${NC} Tmux light-recon window created"
  echo -e "${CYAN}[*]${NC} Switch to window: ${BOLD}--> Light: ${url:0:20}... <--${NC}"
  echo -e "${CYAN}[*]${NC} Results will be in: ${BOLD}$OUTPUT_DIR${NC}"
  echo
  echo -e "${YELLOW}Note:${NC} Light recon appears as normal browser traffic"
  echo -e "${YELLOW}Note:${NC} Screenshots saved to screenshots/ subdirectory"
}

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

  cd "$OUTPUT_DIR"

  echo -e "\n${GREENSTAR} Running httpx...${NC}"
  if command -v httpx &>/dev/null; then
    echo "$url" | httpx -silent -title -tech-detect -status-code -web-server -ip -o httpx-summary.txt
    cat httpx-summary.txt
  fi

  echo -e "\n${GREENSTAR} Running gowitness...${NC}"
  if command -v gowitness &>/dev/null; then
    gowitness single "$url" --screenshot-path=./screenshots/ --disable-logging --timeout 30
    ls -lh screenshots/
  fi

  cd ..

  echo -e "\n${GREEN}✓${NC} Light 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: light-recon <url>"
  exit 1
fi

# Check tools
check_tools

# Run light reconnaissance
run_light_recon "$url"
