#!/bin/sh
# Runs the CI flag checks against valid and broken files and prints each exit code.
# Needs Node.js and Docker. Usage: sh benchmarks/ci-flags/run.sh > benchmarks/ci-flags/results.txt
DIR=$(cd "$(dirname "$0")" && pwd)
cd "$DIR" || exit 1
npm ci --silent >&2
CLI=gofeatureflag/go-feature-flag-cli:v1.58.1
WF=.github/workflows/flags.yml
[ -f "$WF" ] || WF=flags.yml
echo "# $(date -u +%Y-%m-%dT%H:%M:%SZ), node $(node --version), ajv-cli 5.0.0, $CLI, rhysd/actionlint:1.7.12"
check() { label=$1; shift; out=$("$@" 2>&1); code=$?; echo "$label: exit $code"; echo "$out" | sed 's/\x1b\[[0-9;]*m//g' | grep -vE '^\s*$' | head -6 | sed 's/^/    /'; }
AJV="npx ajv validate --spec=draft7 -c ajv-formats -s schema/flags.json -r schema/targeting.json --strict=false --errors=text --all-errors"
for f in flags.flagd.json broken.flagd.json unknown-variant.flagd.json; do
  check "flagd schema, $f" $AJV -d "flags/$f"
done
for f in flags.goff.yaml broken.goff.yaml; do
  check "GO Feature Flag lint, $f" docker run --rm -v "$DIR/flags:/flags" "$CLI" lint "/flags/$f" --format yaml
done
check "flag keys in src-clean/ defined in flags.flagd.json" node check-flag-keys.mjs flags/flags.flagd.json src-clean
check "flag keys in src/ (with a typo) defined in flags.flagd.json" node check-flag-keys.mjs flags/flags.flagd.json src
check "actionlint, $WF" docker run --rm -v "$DIR/$WF:/flags.yml" rhysd/actionlint:1.7.12 -color=false /flags.yml
# The workflow's own ajv command, on Node 22 with a fresh npm cache
for f in flags.flagd.json broken.flagd.json; do
  check "workflow ajv step (node:22, npx), $f" docker run --rm -v "$DIR:/repo" -w /repo node:22-alpine sh -c \
    "npx --yes -p ajv-cli@5.0.0 -p ajv-formats@3.0.1 ajv validate --spec=draft7 -c ajv-formats -s schema/flags.json -r schema/targeting.json -d flags/$f --strict=false"
done
