#!/bin/bash
# ANCOM — Autoritatea Națională pentru Administrare și Reglementare în
# Comunicații. Scrapes the public registry of authorized communications
# providers from ancom.ro.
#
# Mirrors scrape-anre.sh / scrape-bugetar.sh pattern: Infisical Machine
# Identity → env-file → docker run --env-file (NEVER -e $VAR), file deleted
# post-launch.
#
# Idempotent (UPSERT on ancom_id). Safe to run from cron.
#
# Env knobs:
#   LIMIT=0                  (default: 0 = full ~570 operators)
#   MAX_PAGES=0              (default: 0 = all list pages)
#
# Run:
#   sudo MAX_PAGES=2 /opt/vreaudigital/services/seap-scraper/cron/scrape-ancom.sh   # smoke test (2 pages = 20 ids)
#   sudo /opt/vreaudigital/services/seap-scraper/cron/scrape-ancom.sh               # full
set -euo pipefail

LIMIT="${LIMIT:-0}"
MAX_PAGES="${MAX_PAGES:-0}"
LOG=/var/log/vreaudigital-ancom.log

log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG"; }

log "=== ANCOM scrape started (limit=$LIMIT max_pages=$MAX_PAGES) ==="

if docker ps --filter name=vreaudigital-ancom --format '{{.Names}}' | grep -q '^vreaudigital-ancom$'; then
  log "WARN: vreaudigital-ancom already running, skipping this tick"
  exit 0
fi
docker rm -f vreaudigital-ancom 2>/dev/null || true

# ── Fetch DATABASE_URL via Infisical Machine Identity ──
source /opt/vreaudigital/.infisical-mi
TOKEN=$(infisical login --method=universal-auth \
  --domain="$INFISICAL_API_URL" \
  --client-id="$INFISICAL_CLIENT_ID" \
  --client-secret="$INFISICAL_CLIENT_SECRET" \
  --silent --plain)

umask 077
ENVF=$(mktemp /tmp/.vreaudigital-ancom-env.XXXXXX)
DBURL=$(infisical secrets get DATABASE_URL \
  --domain="$INFISICAL_API_URL" \
  --projectId="$INFISICAL_PROJECT_ID" \
  --env="$INFISICAL_ENV" --path="$INFISICAL_PATH" \
  --token="$TOKEN" --plain --silent)
echo "DATABASE_URL=$DBURL" > "$ENVF"
unset DBURL TOKEN

cd /opt/vreaudigital/services/seap-scraper

if [ ! -d node_modules/tsx ]; then
  log "Installing seap-scraper deps..."
  docker run --rm -v "$(pwd):/work" -w /work --user "$(id -u):$(id -g)" \
    node:22-alpine npm install --omit=optional 2>&1 | tee -a "$LOG" >/dev/null
fi

EXTRA_ARGS=""
[ "$LIMIT" -gt 0 ] 2>/dev/null && EXTRA_ARGS="$EXTRA_ARGS --limit=$LIMIT"
[ "$MAX_PAGES" -gt 0 ] 2>/dev/null && EXTRA_ARGS="$EXTRA_ARGS --max-pages=$MAX_PAGES"

CID=$(docker run -d \
  --name vreaudigital-ancom \
  --network host \
  --env-file "$ENVF" \
  -v "$(pwd):/work" \
  -w /work \
  --user "$(id -u):$(id -g)" \
  --restart no \
  node:22-alpine \
  npx tsx src/scrape-ancom.ts $EXTRA_ARGS)
log "container started: $CID"

sleep 3
rm -f "$ENVF"
log "envfile cleaned"

docker wait vreaudigital-ancom >/dev/null
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' vreaudigital-ancom 2>/dev/null || echo "?")
docker logs vreaudigital-ancom 2>&1 | tail -30 | tee -a "$LOG"
log "=== ANCOM scrape done (exit=$EXIT_CODE) ==="

exit "$EXIT_CODE"
