#!/usr/bin/env bash
# Passive subdomain enumeration using public sources (no active scanning).
# Usage: bash scripts/subdomain_enum.sh example.com [--output subdomains.txt]
set -euo pipefail

DOMAIN="${1:?Usage: $0 <domain> [--output file]}"
OUTPUT="${2:-}"

echo "=== Passive Subdomain Enumeration: $DOMAIN ==="
echo ""

SUBS=$(mktemp)

# crt.sh (Certificate Transparency)
echo "--- crt.sh ---"
curl -s "https://crt.sh/?q=%25.${DOMAIN}&output=json" 2>/dev/null | \
  jq -r '.[].name_value' 2>/dev/null | sort -u >> "$SUBS" || echo "  crt.sh unavailable"

# DNS brute (common prefixes)
echo "--- Common prefixes ---"
for prefix in www mail ftp vpn api dev staging test admin portal blog shop app cdn; do
  result=$(dig +short "${prefix}.${DOMAIN}" 2>/dev/null)
  if [ -n "$result" ]; then
    echo "${prefix}.${DOMAIN}" >> "$SUBS"
  fi
done

# subfinder if available
if command -v subfinder &>/dev/null; then
  echo "--- subfinder ---"
  subfinder -d "$DOMAIN" -silent 2>/dev/null >> "$SUBS"
fi

# Deduplicate and sort
sort -u "$SUBS" -o "$SUBS"
COUNT=$(wc -l < "$SUBS")

echo ""
echo "=== Found $COUNT unique subdomains ==="
cat "$SUBS"

if [ -n "$OUTPUT" ]; then
  cp "$SUBS" "$OUTPUT"
  echo ""
  echo "Saved to: $OUTPUT"
fi

rm -f "$SUBS"
