#!/usr/bin/env bash
# Nmap service enumeration with safe defaults for authorized engagements.
# Usage: bash scripts/service_scan.sh <target> [--top-ports N] [--output-dir DIR]
set -euo pipefail

TARGET="${1:?Usage: $0 <target> [--top-ports N] [--output-dir DIR]}"
TOP_PORTS="${2:-1000}"
OUTPUT_DIR="${3:-.}"

echo "=== Service Scan: $TARGET (top $TOP_PORTS ports) ==="
echo "⚠️  Ensure you have written authorization before scanning."
echo ""

# TCP SYN scan with version detection
nmap -sS -sV -sC --top-ports "$TOP_PORTS" \
  -oN "${OUTPUT_DIR}/nmap-tcp-${TARGET}.txt" \
  -oX "${OUTPUT_DIR}/nmap-tcp-${TARGET}.xml" \
  "$TARGET"

echo ""
echo "--- Quick Wins ---"
# Parse for common high-value services
grep -E "open.*http|open.*ssh|open.*smb|open.*rdp|open.*ftp|open.*mysql|open.*mssql|open.*postgres" \
  "${OUTPUT_DIR}/nmap-tcp-${TARGET}.txt" 2>/dev/null || echo "  No common services found"

echo ""
echo "Results saved to ${OUTPUT_DIR}/nmap-tcp-${TARGET}.{txt,xml}"
