#!/bin/bash
# Daily delta enrichment from ANAF webservicesp v9.
# Runs the tsx script inside a node:22-alpine container so satra doesn't
# need node installed at host level. DATABASE_URL is fetched fresh from
# Infisical and passed via --env-file (mode 600, deleted right after the
# container starts) — never on the docker run command line.
#
# Tier selection: pass TIER=daily|full|bulk as env (default: daily).
# Concurrency: pass ANAF_CONCURRENCY=N (default: 2).
#
# Idempotent. Safe to run from cron.

set -euo pipefail

TIER="${TIER:-daily}"
ANAF_CONCURRENCY="${ANAF_CONCURRENCY:-2}"
LOG=/var/log/vreaudigital-anaf.log

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

log "=== ANAF enrichment started (tier=$TIER, concurrency=$ANAF_CONCURRENCY) ==="

# Bail if a previous run is still going — daily/full tier should always
# finish well under 24h, so a still-running container means trouble.
if docker ps --filter name=vreaudigital-anaf --format '{{.Names}}' | grep -q '^vreaudigital-anaf$'; then
  log "WARN: vreaudigital-anaf already running, skipping this tick"
  exit 0
fi
docker rm -f vreaudigital-anaf 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-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

# ── Launch detached docker container ──
cd /opt/vreaudigital/services/seap-scraper

# Make sure node_modules exists (first run on a fresh host).
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

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

# Daemon has read --env-file by the time `docker run -d` returns.
sleep 3
rm -f "$ENVF"
log "envfile cleaned"

# Wait synchronously so systemd Type=oneshot accurately captures runtime.
docker wait vreaudigital-anaf >/dev/null
EXIT_CODE=$(docker inspect -f '{{.State.ExitCode}}' vreaudigital-anaf 2>/dev/null || echo "?")
docker logs vreaudigital-anaf 2>&1 | tail -5 | tee -a "$LOG"
log "=== ANAF enrichment done (exit=$EXIT_CODE) ==="

exit "$EXIT_CODE"
