#!/usr/bin/env bash
# Publish a release to Gitea (git.lazypugs.com).
#
# Auth: needs a Gitea token with 'write:repository'. Never hardcode it.
#   export GITEA_TOKEN=...        # from your shell / password manager
#   ./tools/publish.sh            # or: GAME=GundamBreaker4 TAG=v1.0.1 ./tools/publish.sh
#
# Steps: build the game's zip -> push branch+tag -> create release -> upload asset.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"; cd "$HERE"

HOST="${GITEA_HOST:-https://git.lazypugs.com}"
OWNER="${GITEA_OWNER:-ckoch}"
REPO="${GITEA_REPO:-UltraWidePatches}"
# GAME may be a space-separated list; empty/"all" = every game in games/
GAME="${GAME:-all}"
if [ "$GAME" = "all" ]; then
  GAME=$(for d in games/*/; do [ -f "$d/game.conf" ] && basename "$d"; done | tr '\n' ' ')
fi
TAG="${TAG:-v1.0.0}"
# Single game -> its own README; multiple -> the collection README.
if [ "$(echo "$GAME" | wc -w)" -eq 1 ] && [ -f "games/$GAME/README.md" ]; then
  NOTES="${NOTES:-games/$GAME/README.md}"
else
  NOTES="${NOTES:-README.md}"
fi
[ -f "$NOTES" ] || NOTES="README.md"
API="$HOST/api/v1"

[ -n "${GITEA_TOKEN:-}" ] || { echo "[!] GITEA_TOKEN is not set. Create one at $HOST/user/settings/applications (scope: write:repository)"; exit 1; }
AUTH=(-H "Authorization: token $GITEA_TOKEN")
echo "[+] Games in this release: $GAME"

# 1. build every artifact -- do NOT swallow output; a failure here used to exit
# the whole script silently because stdout went to /dev/null under `set -e`.
ZIPS=""
for g in $GAME; do
  if ! bash tools/build_release.sh "$g"; then
    echo "[!] build_release.sh failed for game '$g' (see above)"; exit 1
  fi
  z="dist/${g}_UltraWide_Fix.zip"
  [ -f "$z" ] || { echo "[!] build produced no $z"; exit 1; }
  ZIPS="$ZIPS $z"
done
echo "[+] Built:$ZIPS"

# 2. push code + tag
git push origin main
if ! git rev-parse -q --verify "refs/tags/$TAG" >/dev/null; then
  git tag -a "$TAG" -m "$TAG"
  echo "[+] Created tag $TAG at $(git rev-parse --short HEAD)"
fi
git push origin "$TAG" 2>&1 | tail -1

# 3. create the release (or reuse if it already exists)
REL_ID=$(curl -sf "${AUTH[@]}" "$API/repos/$OWNER/$REPO/releases/tags/$TAG" 2>/dev/null \
         | python3 -c "import sys,json;print(json.load(sys.stdin)['id'])" 2>/dev/null || true)

if [ -z "$REL_ID" ]; then
  BODY=$(python3 -c "import json,sys;print(json.dumps(open(sys.argv[1]).read()))" "$NOTES")
  REL_ID=$(curl -sf "${AUTH[@]}" -H "Content-Type: application/json" \
      -d "{\"tag_name\":\"$TAG\",\"name\":\"$TAG\",\"body\":$BODY}" \
      "$API/repos/$OWNER/$REPO/releases" \
    | python3 -c "import sys,json;print(json.load(sys.stdin)['id'])")
  echo "[+] Created release $TAG (id=$REL_ID)"
else
  echo "[i] Release $TAG exists (id=$REL_ID); replacing assets"
fi

# 4. upload each zip, replacing any same-named asset already attached
for z in $ZIPS; do
  n=$(basename "$z")
  OLD=$(curl -sf "${AUTH[@]}" "$API/repos/$OWNER/$REPO/releases/$REL_ID" \
        | ZIPNAME="$n" python3 -c "
import sys, json, os
d = json.load(sys.stdin)
want = os.environ['ZIPNAME']
print(next((str(a['id']) for a in d.get('assets', []) if a['name'] == want), ''))" 2>/dev/null || true)
  [ -n "$OLD" ] && curl -sf -X DELETE "${AUTH[@]}" \
      "$API/repos/$OWNER/$REPO/releases/$REL_ID/assets/$OLD" >/dev/null && echo "[i] replaced $n"
  curl -sf "${AUTH[@]}" -F "attachment=@$z" \
    "$API/repos/$OWNER/$REPO/releases/$REL_ID/assets?name=$n" >/dev/null
  echo "[+] Uploaded $n"
done

echo
echo "[+] Done: $HOST/$OWNER/$REPO/releases/tag/$TAG"
