#!/usr/bin/env bash

set -euo pipefail

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

usage() {
  cat <<'EOF'
Usage: bin/deploy-prod.sh

Confirm and trigger a my-note deployment through GitHub Actions.
Update the current server branch in /var/www/html/my-note with a fast-forward pull.
Print the URL of the triggered workflow run.
Requires GitHub CLI (gh) authenticated with access to this repository.
Authenticate with: gh auth login

Options:
  -h, --help        Show this help and exit.
EOF
}

if [[ $# -gt 0 ]]; then
  if [[ $# -eq 1 && ( "$1" == -h || "$1" == --help ) ]]; then
    usage
    exit 0
  fi

  echo "This command does not accept arguments. It updates the current server branch." >&2
  usage >&2
  exit 1
fi

cd "$ROOT_DIR"

if ! command -v gh >/dev/null 2>&1; then
  echo "gh command not found. Install GitHub CLI and run 'gh auth login'." >&2
  exit 1
fi

if ! command -v git >/dev/null 2>&1; then
  echo "git command not found. Please install Git." >&2
  exit 1
fi

echo 'my-note deployment: update the current branch in /var/www/html/my-note.'
printf 'Start deployment? [y/N] ' >&2

if ! IFS= read -r CONFIRMATION; then
  echo "Deployment canceled."
  exit 0
fi

case "$CONFIRMATION" in
  y|Y|yes|YES|Yes)
    ;;
  *)
    echo "Deployment canceled."
    exit 0
    ;;
esac

echo 'Requesting my-note deployment...'

RUN_URL="$(gh api --method POST \
  'repos/{owner}/{repo}/actions/workflows/update-server.yml/dispatches' \
  --header 'Accept: application/vnd.github+json' \
  --header 'X-GitHub-Api-Version: 2026-03-10' \
  --raw-field ref=main \
  --jq '.html_url // empty')"

if [[ -z "$RUN_URL" ]]; then
  echo "No run URL was returned. Check GitHub Actions for the requested deployment." >&2
  exit 1
fi

echo "Deployment requested. Check progress in GitHub Actions:"
printf '%s\n' "$RUN_URL"
