#!/usr/bin/env bash

set -euo pipefail

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  echo "Usage: bash scripts/trigger-gitea-pipeline.sh [remote] [tag]"
  echo ""
  echo "Examples:"
  echo "  bash scripts/trigger-gitea-pipeline.sh"
  echo "  bash scripts/trigger-gitea-pipeline.sh gitea latest"
  echo "  bash scripts/trigger-gitea-pipeline.sh gitea v2026.05.15.1"
  exit 0
fi

REMOTE="${1:-gitea}"
TAG="${2:-latest}"

if ! git rev-parse --git-dir >/dev/null 2>&1; then
  echo "[ERROR] Current directory is not a git repository."
  exit 1
fi

if ! git remote get-url "$REMOTE" >/dev/null 2>&1; then
  echo "[ERROR] Remote '$REMOTE' does not exist."
  echo "Available remotes:"
  git remote -v
  exit 1
fi

HEAD_SHA="$(git rev-parse --short HEAD)"
MESSAGE="manual trigger: ${TAG} $(date '+%F %T')"

echo "[INFO] HEAD: ${HEAD_SHA}"
echo "[INFO] Recreate annotated tag '${TAG}'"
git tag -fa "$TAG" -m "$MESSAGE"

echo "[INFO] Push '${TAG}' to remote '${REMOTE}' (force update)"
git push "$REMOTE" "refs/tags/${TAG}" --force

echo "[INFO] Verify remote tag reference"
git ls-remote --tags "$REMOTE" "refs/tags/${TAG}"

echo "[DONE] Pipeline trigger request sent by updating tag '${TAG}'."
