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

RUN_ID="${PENTEST_RUN_ID:-manual}"
ARTIFACT_DIR="${PENTEST_ARTIFACT_DIR:-.paqad/pentest/runs/${RUN_ID}/artifacts}"
RUNTIME_DIR="${ARTIFACT_DIR}/runtime"
TARGET_URL="${PENTEST_TARGET_URL:-}"
FIXTURE_JSON="${PENTEST_RUNTIME_CHECKS_FIXTURE:-}"

mkdir -p "${RUNTIME_DIR}"

if [ -z "${TARGET_URL}" ]; then
  node - <<'NODE' > "${RUNTIME_DIR}/runtime-checks.json"
console.log(JSON.stringify({
  target_url: null,
  reachable: false,
  detail: 'No target URL configured for runtime checks.',
  checks: [],
}, null, 2));
NODE
  exit 0
fi

if [ -n "${FIXTURE_JSON}" ]; then
  node - <<'NODE' > "${RUNTIME_DIR}/runtime-checks.json"
const payload = JSON.parse(process.env.PENTEST_RUNTIME_CHECKS_FIXTURE);
console.log(JSON.stringify(payload, null, 2));
NODE
  echo "runtime checks complete"
  exit 0
fi

node - <<'NODE' > "${RUNTIME_DIR}/runtime-checks.json"
const targetUrl = process.env.PENTEST_TARGET_URL;
const candidates = ['/', '/up', '/admin', '/debug', '/telescope', '/horizon', '/_debugbar/open', '/__clockwork', '/.env'];

async function fetchCheck(path) {
  try {
    const response = await fetch(new URL(path, targetUrl), {
      method: 'GET',
      redirect: 'manual',
      signal: AbortSignal.timeout(3000),
    });
    return { path, status: response.status };
  } catch {
    return { path, status: 0 };
  }
}

const checks = [];
for (const candidate of candidates) {
  checks.push(await fetchCheck(candidate));
}
const reachable = checks.some((entry) => entry.path === '/' && entry.status > 0);
console.log(JSON.stringify({
  target_url: targetUrl,
  reachable,
  detail: reachable ? 'Runtime checks completed.' : 'Runtime target did not answer base-path checks.',
  checks,
}, null, 2));
NODE

echo "runtime checks complete"
