#!/usr/bin/env bash
# Upload the built macOS artifacts to a Gitea release. No runners, no CI.
# Auth comes from the macOS keychain (same creds `git` uses to push).
# Usage: ./scripts/gitea-release.sh [v0.1.0]
# Requires: jq, curl, and a prior `npm run tauri build`.
set -euo pipefail

GITEA_URL="https://gitea.jms.rocks"
OWNER_REPO="jameshtwose/dm-pal"
API="$GITEA_URL/api/v1/repos/$OWNER_REPO"
HOST="${GITEA_URL#https://}"

# Auth: explicit token wins, else pull from the git credential helper (keychain).
auth_header() {
  if [ -n "${GITEA_TOKEN:-}" ]; then
    printf 'Authorization: token %s' "$GITEA_TOKEN"; return
  fi
  creds=$(git credential fill <<< "protocol=https
host=$HOST" 2>/dev/null || true)
  user=$(printf '%s\n' "$creds" | sed -n 's/^username=//p')
  pass=$(printf '%s\n' "$creds" | sed -n 's/^password=//p')
  [ -n "$pass" ] || { echo "no creds in keychain and GITEA_TOKEN unset"; exit 1; }
  printf 'Authorization: Basic %s' "$(printf '%s:%s' "$user" "$pass" | base64)"
}

TAG="${1:-v$(jq -r .version package.json)}"

DMG=$(ls -t src-tauri/target/release/bundle/dmg/*.dmg | head -1)
APP_BUNDLE=$(ls -d src-tauri/target/release/bundle/macos/*.app | head -1)
[ -f "$DMG" ]        || { echo "no dmg found — run 'npm run tauri build' first"; exit 1; }
[ -d "$APP_BUNDLE" ] || { echo "no .app found"; exit 1; }

# ponytail: ship the dmg as the installer; also zip the .app for unmanaged
# installs / inspection. Skip if zip already present.
ZIP="${APP_BUNDLE%.app}.zip"
[ -f "$ZIP" ] || ditto -c -k --keepParent "$APP_BUNDLE" "$ZIP"

AUTH=$(auth_header)

echo "Creating release $TAG ..."
REL=$(curl -sf -X POST "$API/releases" \
  -H "$AUTH" -H "Content-Type: application/json" \
  -d "$(jq -n --arg t "$TAG" --arg n "$TAG" \
        '{tag_name:$t, name:$n, body:"DM-Pal macOS build.", draft:false, prerelease:false}')")
RID=$(echo "$REL" | jq -r .id)
[ "$RID" != "null" ] || { echo "release create failed: $REL"; exit 1; }
echo "release id=$RID"

for f in "$DMG" "$ZIP"; do
  echo "attaching $(basename "$f") ..."
  curl -sf -X POST "$API/releases/$RID/assets?name=$(basename "$f")" \
    -H "$AUTH" -F "attachment=@$f" -o /dev/null
done

echo "done -> $GITEA_URL/$OWNER_REPO/releases/tag/$TAG"