#!/usr/bin/env bash
# dsflow_ci - continuous integration for the DesignSync trunk.
# Run from cron (e.g. hourly) or a check-in trigger. It:
#   1. populates a clean workspace at Trunk:Latest
#   2. runs sanity on every config (+ CI-only suites)
#   3. green -> immutable snapshot tag + moves the working tag
#      red   -> leaves working tag alone, mails everyone who checked in since last green
set -euo pipefail

CI_WS="${CI_WS:-/scratch/dsflow_ci/ws}"
export WS_ROOT="$CI_WS"
# shellcheck source=/dev/null
source "${DSFLOW_CONF:-$CI_WS/flow/dsflow.conf}"
mkdir -p "$CI_STATE"

exec 9>"$CI_STATE/.run.lock"
flock -n 9 || { echo "dsflow_ci: previous run still active"; exit 0; }

cd "$CI_WS"
start="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
snap="sanity_$(date +%Y%m%d_%H%M)"

# Snapshot Trunk:Latest. Anything checked in after this pop is NOT tested
# and will NOT be tagged, because tags apply to the versions in this workspace.
dssc pop -rec -force -version "$TRUNK_SEL" .

ok=1
for cfg in $SANITY_CONFIGS $CI_EXTRA_CONFIGS; do
  run_sanity "$cfg" > "$CI_STATE/log_$cfg" 2>&1 || { ok=0; echo "FAIL: $cfg"; }
done

last_green="$(cat "$CI_STATE/last_green" 2>/dev/null || echo 1970-01-01T00:00:00Z)"

if ((ok)); then
  dssc tag -rec "$snap" .                       # immutable, for bisecting later
  dssc tag -rec -replace "$WORKING_TAG" .       # VERIFY: flag to move an existing tag
  echo "$start" > "$CI_STATE/last_green"
  echo "dsflow_ci: GREEN - '$WORKING_TAG' moved to $snap"
else
  suspects="$(awk -F'\t' -v t="$last_green" -v s="$start" '$1>t && $1<=s {print $2": "$4}' "$CHECKIN_LOG")"
  users="$(awk -F'\t' -v t="$last_green" -v s="$start" '$1>t && $1<=s {print $2}' "$CHECKIN_LOG" | sort -u | tr '\n' ' ')"
  {
    echo "Trunk sanity failed at $start. '$WORKING_TAG' was NOT moved."
    echo "Logs: $CI_STATE/log_*"
    echo; echo "Check-ins since last green ($last_green):"; echo "$suspects"
  } | mail -s "[dsflow] trunk sanity RED" "$CI_NOTIFY" $users
  exit 1
fi
