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

# Script Name: recon.sh
# Description: Network/host reconnaissance with tmux orchestration
# Usage: recon <target>
# Creates tmux window with parallel nmap scans and enum4linux

VERSION="2.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}recon${NC} - Network Reconnaissance Script v${VERSION}"
  echo
  echo -e "${BOLD}USAGE:${NC}"
  echo "  recon <target>"
  echo
  echo -e "${BOLD}DESCRIPTION:${NC}"
  echo "  Creates tmux window with 3 panes running parallel reconnaissance:"
  echo "  - Pane 1: nmap service scan + version detection"
  echo "  - Pane 2: nmap vulnerability scan + full port scan"
  echo "  - Pane 3: enum4linux-ng (SMB enumeration)"
  echo
  echo -e "${BOLD}EXAMPLE:${NC}"
  echo "  recon 10.10.10.5"
  echo "  recon target.htb"
  echo
  echo -e "${BOLD}OUTPUT:${NC}"
  echo "  All results saved to: ./recon-<target>-<timestamp>/"
}

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

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

  # Optional tools
  if ! command -v naabu &>/dev/null; then
    echo -e "${YELLOW}⚠${NC} naabu not found (optional - using pure nmap)"
  fi

  if ! command -v docker &>/dev/null; then
    echo -e "${YELLOW}⚠${NC} docker not found (skipping enum4linux-ng)"
  fi

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

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

  OUTPUT_DIR="recon-${clean_target}-${timestamp}"
  mkdir -p "$OUTPUT_DIR"

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

# Main recon function
run_recon() {
  local target="$1"

  echo -e "${CYAN}${BOLD}"
  echo "╔════════════════════════════════════════════════════════════╗"
  echo "║               Network Reconnaissance                       ║"
  echo "║                    Target: $target"
  echo "╚════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"

  # Create output directory
  setup_output_dir "$target"

  # Check if in tmux
  if [[ -z "${TMUX:-}" ]]; then
    echo -e "${YELLOW}⚠${NC} Not in tmux session - results will be in terminal"
    run_scans_sequential "$target"
    return
  fi

  # Create tmux window
  tmux new-window -n "<<Recon: $target>>"

  # Split into 3 panes
  # Bottom pane (pane 0)
  tmux split-window -v

  # Top left pane (pane 1)
  tmux select-pane -t 0
  tmux split-window -h

  # Top right pane (pane 2)
  tmux select-pane -t 1
  tmux split-window -h

  # Pane 0 (bottom): Quick scan + detailed scan
  tmux select-pane -t 0
  if command -v naabu &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting quick port discovery with naabu...${NC}' && naabu -host $target -nmap-cli 'nmap -A -T4 -oA nmap_quick' && echo -e '\n${GREENSTAR} Starting detailed scan...${NC}\n' && naabu -host $target -nmap-cli 'nmap -sV -sC -Pn -oN nmap_detailed'" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting nmap scan...${NC}' && nmap -sV -sC -T4 -oA nmap_quick $target && echo -e '\n${GREENSTAR} Starting detailed scan...${NC}\n' && nmap -sV -sC -Pn -oN nmap_detailed $target" C-m
  fi

  # Pane 1 (top left): Vulnerability scan + full port scan
  tmux select-pane -t 1
  if command -v naabu &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting vulnerability scan...${NC}' && naabu -host $target -nmap-cli 'nmap --script vuln -Pn -oN nmap_vuln' && echo -e '\n${GREENSTAR} Starting full port scan (all 65535)...${NC}\n' && nmap -p- -T4 $target -oN nmap_fullports" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting vulnerability scan...${NC}' && nmap --script vuln -Pn -oN nmap_vuln $target && echo -e '\n${GREENSTAR} Starting full port scan...${NC}\n' && nmap -p- -T4 $target -oN nmap_fullports" C-m
  fi

  # Pane 2 (top right): enum4linux-ng
  tmux select-pane -t 2
  if command -v docker &>/dev/null; then
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${GREENSTAR} Starting enum4linux-ng (SMB enumeration)...${NC}' && docker run --rm -t enum4linux-ng -A -C $target -oY enum4linux-ng.yaml | tee enum4linux-ng.txt" C-m
  else
    tmux send-keys "cd '$PWD/$OUTPUT_DIR' && echo -e '${YELLOW}⚠ Docker not available - skipping enum4linux-ng${NC}' && echo 'Install docker to enable SMB enumeration' && sleep 5" C-m
  fi

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

  echo
  echo -e "${GREEN}✓${NC} Tmux recon window created"
  echo -e "${CYAN}[*]${NC} Switch to window: ${BOLD}<<Recon: $target>>${NC}"
  echo -e "${CYAN}[*]${NC} Results will be in: ${BOLD}$OUTPUT_DIR${NC}"
}

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

  cd "$OUTPUT_DIR"

  echo -e "\n${GREENSTAR} Running nmap service scan...${NC}"
  if command -v naabu &>/dev/null; then
    naabu -host "$target" -nmap-cli 'nmap -sV -sC -T4 -oA nmap_quick'
  else
    nmap -sV -sC -T4 -oA nmap_quick "$target"
  fi

  echo -e "\n${GREENSTAR} Running vulnerability scan...${NC}"
  nmap --script vuln -Pn -oN nmap_vuln "$target"

  if command -v docker &>/dev/null; then
    echo -e "\n${GREENSTAR} Running enum4linux-ng...${NC}"
    docker run --rm -t enum4linux-ng -A -C "$target" -oY enum4linux-ng.yaml | tee enum4linux-ng.txt
  fi

  cd ..

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

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

target="$1"

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

# Check tools
check_tools

# Run reconnaissance
run_recon "$target"
