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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
VERSION="${1:?usage: update_homebrew_tap.sh <version> <dmg_path>}"
DMG_PATH="${2:?usage: update_homebrew_tap.sh <version> <dmg_path>}"
TAP_DIR="${HOMEBREW_TAP_DIR:-$ROOT_DIR/homebrew-tap}"
CASK_FILE="$TAP_DIR/Casks/ikeymon.rb"

if [[ ! -d "$TAP_DIR/.git" ]]; then
  echo "❌ Homebrew tap repo not found at $TAP_DIR"
  exit 1
fi

if [[ ! -f "$CASK_FILE" ]]; then
  echo "❌ Homebrew cask file not found at $CASK_FILE"
  exit 1
fi

if [[ ! -f "$DMG_PATH" ]]; then
  echo "❌ DMG artifact not found at $DMG_PATH"
  exit 1
fi

if [[ -n "$(git -C "$TAP_DIR" status --porcelain)" ]]; then
  echo "❌ Homebrew tap repo has uncommitted changes: $TAP_DIR"
  exit 1
fi

SHA256="$(shasum -a 256 "$DMG_PATH" | awk '{print $1}')"

python3 - <<'PY' "$CASK_FILE" "$VERSION" "$SHA256"
from pathlib import Path
import re
import sys

cask_path = Path(sys.argv[1])
version = sys.argv[2]
sha256 = sys.argv[3]
content = cask_path.read_text(encoding="utf-8")

content, version_count = re.subn(r'version "[^"]+"', f'version "{version}"', content, count=1)
content, sha_count = re.subn(r'sha256 "[^"]+"', f'sha256 "{sha256}"', content, count=1)

if version_count != 1 or sha_count != 1:
    raise SystemExit("Failed to update version or sha256 in cask file")

cask_path.write_text(content, encoding="utf-8")
PY

ruby -c "$CASK_FILE" >/dev/null

if git -C "$TAP_DIR" diff --quiet -- "$CASK_FILE"; then
  echo "ℹ️ Homebrew tap already points to iKeyMon ${VERSION}"
  exit 0
fi

git -C "$TAP_DIR" add "$CASK_FILE"
git -C "$TAP_DIR" commit -m "cask: update ikeymon to ${VERSION}"
git -C "$TAP_DIR" push origin master

echo "✅ Updated Homebrew tap to iKeyMon ${VERSION}"
