#!/bin/sh
set -e
cd "$(dirname "$0")"
if [ ! -f ./.env ]; then
  echo "ERROR: ./.env not found in $(pwd)" >&2
  echo "Expected at least: CF_API_KEY=<your CurseForge token>" >&2
  exit 1
fi
set -a
. ./.env
set +a
echo "=== Localization parity gate ==="
_locdir=""
for _d in Localization Locales; do
  if [ -d "$_d" ]; then _locdir="$_d"; break; fi
done
if [ -n "$_locdir" ] && [ -f "$_locdir/enUS.lua" ]; then
  _base=$(mktemp)
  grep -oE 'L\["[^"]+"\]' "$_locdir/enUS.lua" 2>/dev/null | sort -u > "$_base" || true
  _gatefail=0
  for _f in "$_locdir"/*.lua; do
    [ -e "$_f" ] || continue
    [ "$_f" = "$_locdir/enUS.lua" ] && continue
    _cur=$(mktemp)
    grep -oE 'L\["[^"]+"\]' "$_f" 2>/dev/null | sort -u > "$_cur" || true
    _miss=$(comm -23 "$_base" "$_cur")
    rm -f "$_cur"
    if [ -n "$_miss" ]; then
      echo "  MISSING in $(basename "$_f"): $(echo $_miss | tr '\n' ' ')"
      _gatefail=1
    fi
    if command -v luac >/dev/null 2>&1; then
      luac -p "$_f" >/dev/null 2>&1 || { echo "  LUA SYNTAX FAIL: $_f"; _gatefail=1; }
    fi
  done
  rm -f "$_base"
  if [ "$_gatefail" -ne 0 ]; then
    echo "Release aborted: localization gate failed. Translate the missing keys into every locale first." >&2
    exit 1
  fi
  echo "  PASS: every locale at full key parity with enUS"
else
  echo "  (no locale dir or no enUS.lua, skipping)"
fi
status=0
./.release/release.sh "$@" || status=$?
if [ "$status" -eq 0 ]; then
  rm -f .release/*.zip
fi
exit "$status"
