#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
REMOTE_NAME="${1:-origin}"

if [[ -n "${SKIP_RELEASE:-}" ]]; then
  echo "⚙️  SKIP_RELEASE set — skipping automated release build."
  exit 0
fi

should_release=false
release_local_ref=""
release_remote_ref=""
while read -r local_ref local_sha remote_ref remote_sha; do
  [[ -z "${local_ref:-}" ]] && continue
  if [[ "$local_ref" == "refs/heads/master" || "$remote_ref" == "refs/heads/master" ]]; then
    should_release=true
    release_local_ref="$local_ref"
    release_remote_ref="${remote_ref:-refs/heads/master}"
  fi
done

if [[ "$should_release" != true ]]; then
  current_branch="$(git -C "$ROOT_DIR" symbolic-ref --short -q HEAD || true)"
  if [[ "$current_branch" == "master" ]]; then
    should_release=true
    release_local_ref="refs/heads/master"
    release_remote_ref="refs/heads/master"
  fi
fi

if [[ "$should_release" != true ]]; then
  exit 0
fi

echo "🚀 Detected push to master — bumping version and building release..."
NEW_VERSION="$("$ROOT_DIR/scripts/bump_version.sh")"
echo "🔢 marketing_version -> ${NEW_VERSION}"
"$ROOT_DIR/scripts/sync_version.sh"

git -C "$ROOT_DIR" add "$ROOT_DIR/version.json" "$ROOT_DIR/iKeyMon.xcodeproj/project.pbxproj"

"$ROOT_DIR/scripts/build_release.sh"

git -C "$ROOT_DIR" add "$ROOT_DIR/version.json" "$ROOT_DIR/iKeyMon.xcodeproj/project.pbxproj" "$ROOT_DIR/Sparkle/appcast.xml"

if git -C "$ROOT_DIR" diff --cached --quiet; then
  echo "⚠️ No release changes detected; skipping release commit."
else
  git -C "$ROOT_DIR" commit -m "chore: release ${NEW_VERSION}"
  echo "📝 Committed release ${NEW_VERSION}."
fi

echo "📤 Pushing release commit..."
if SKIP_RELEASE=1 git -C "$ROOT_DIR" push "$REMOTE_NAME" "${release_local_ref:-refs/heads/master}:${release_remote_ref:-refs/heads/master}"; then
  echo "✅ Release ${NEW_VERSION} pushed. Original push cancelled (already done)."
  exit 1
else
  echo "❌ Failed to push release ${NEW_VERSION}. Please resolve manually."
  exit 1
fi
