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

RUN_ID="${PENTEST_RUN_ID:-manual}"
ARTIFACT_DIR="${PENTEST_ARTIFACT_DIR:-.paqad/pentest/runs/${RUN_ID}/artifacts}"
SURFACE_DIR="${ARTIFACT_DIR}/surface"

mkdir -p "${SURFACE_DIR}"

if [ -d "docs/modules" ] && command -v node >/dev/null 2>&1; then
  node - <<'NODE' > "${SURFACE_DIR}/module-surface.json"
const fs = require('fs');
const path = require('path');
const root = path.join(process.cwd(), 'docs', 'modules');
if (!fs.existsSync(root)) {
  console.log(JSON.stringify([], null, 2));
  process.exit(0);
}
const modules = fs.readdirSync(root, { withFileTypes: true })
  .filter((entry) => entry.isDirectory())
  .map((entry) => entry.name)
  .sort()
  .map((name) => ({
    module: name,
    files: ['business.md', 'technical.md', 'api/endpoints.md', 'integration/contracts.md', 'error-catalog.md']
      .map((relativePath) => path.join(root, name, relativePath))
      .filter((candidate) => fs.existsSync(candidate))
      .map((candidate) => path.relative(process.cwd(), candidate)),
  }));
console.log(JSON.stringify(modules, null, 2));
NODE
fi

if [ -f "artisan" ] && command -v php >/dev/null 2>&1; then
  php artisan route:list --json > "${SURFACE_DIR}/routes.json" 2>"${SURFACE_DIR}/routes.stderr" || true
fi

if command -v rg >/dev/null 2>&1; then
  rg -n --no-heading '(debug|telescope|clockwork|horizon|admin)' routes app src \
    > "${SURFACE_DIR}/suspicious-surface.txt" 2>/dev/null || true
else
  touch "${SURFACE_DIR}/suspicious-surface.txt"
fi

echo "surface enumeration complete"
