#!/bin/sh
# Weekly scheduled: pull + SonarQube scan for repos with recent Bitbucket commits.
# Crontab: Thursday 01:00 — see CLAUDE.md or crontab -l.
# Safe under `sh` (dash) and bash; use LF line endings only.

set -e
ROOT=$(cd "$(dirname "$0")/.." && pwd)
cd "$ROOT"
# SonarJS needs `node` on PATH (cron does not load nvm.sh). Use newest nvm install if present.
if [ -d "$HOME/.nvm/versions/node" ]; then
  NVM_BIN=$(ls -1d "$HOME/.nvm/versions/node"/*/bin 2>/dev/null | sort -V | tail -1)
  if [ -n "$NVM_BIN" ] && [ -d "$NVM_BIN" ]; then
    PATH="$NVM_BIN:$PATH"
  fi
fi
# Typical Sonar Scanner install; Python also resolves scanner binary in sonarqube_scanner.py
export PATH="/usr/local/bin:/usr/bin:/bin:/opt/sonar-scanner/bin:$PATH"

if [ -f "$ROOT/.env" ]; then
  set -a
  # shellcheck disable=SC1090
  . "$ROOT/.env"
  set +a
fi

# Bitbucket lookback (matches WEEKLY_SCAN_DAYS / scanning.weekly_scan_days)
export WEEKLY_SCAN_DAYS="${WEEKLY_SCAN_DAYS:-14}"

LOG_DIR="$ROOT/logs"
mkdir -p "$LOG_DIR"
LOG_FILE="$LOG_DIR/cron_weekly_scan_recent_$(date +%Y%m%d_%H%M%S).log"

exec /usr/bin/python3 "$ROOT/src/scan_recent.py" >>"$LOG_FILE" 2>&1
