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

# Usage: ./scripts/deploy-release.sh v0.0.1
# Requires: curl, tar, (optional) rsync
#
# Auth token: set RELEASE_TOKEN env var or create /etc/sirh-release-token
umask 002

TAG="${1:-}"
if [ -z "$TAG" ]; then
  echo "Usage: $0 v0.0.1" >&2
  exit 1
fi

REPO_OWNER="MALIO-DEV"
REPO_NAME="SIRH"
GITEA_API="https://gitea.malio.fr/api/v1"
DEPLOY_DIR="/var/www/sirh"

if [ -f /etc/sirh-release-token ] && [ -z "${RELEASE_TOKEN:-}" ]; then
  RELEASE_TOKEN="$(cat /etc/sirh-release-token)"
fi

tmp_dir="$(mktemp -d)"
cleanup() {
  rm -rf "$tmp_dir"
}
trap cleanup EXIT

release_json="$tmp_dir/release.json"
curl_opts=(-sS)
if [ -n "${RELEASE_TOKEN:-}" ]; then
  curl_opts+=(-H "Authorization: token ${RELEASE_TOKEN}")
fi
curl "${curl_opts[@]}" \
  "${GITEA_API}/repos/${REPO_OWNER}/${REPO_NAME}/releases/tags/${TAG}" \
  -o "$release_json"

asset_url="$(python3 - "$release_json" <<'PY'
import json, sys
data = json.load(open(sys.argv[1], 'r'))
assets = data.get("assets", [])
for a in assets:
    name = a.get("name", "")
    if name.startswith("sirh-") and name.endswith(".tar.gz"):
        print(a.get("browser_download_url", ""))
        break
PY
)"

if [ -z "$asset_url" ]; then
  echo "Release asset not found for tag ${TAG}" >&2
  exit 1
fi

archive="$tmp_dir/artefact.tar.gz"
curl "${curl_opts[@]}" -L "$asset_url" -o "$archive"

tar -xzf "$archive" -C "$tmp_dir"

if command -v rsync >/dev/null 2>&1; then
  rsync -a --delete --no-perms --no-owner --no-group \
    --exclude ".env" \
    --exclude ".env.local" \
    --exclude "config/jwt" \
    --exclude "var" \
    "$tmp_dir"/ "$DEPLOY_DIR"/
else
  cp -a "$tmp_dir"/. "$DEPLOY_DIR"/
fi

# Ensure Nginx can traverse the deploy path.
chmod o+rx "$(dirname "$DEPLOY_DIR")" "$DEPLOY_DIR" 2>/dev/null || true

echo "Release ${TAG} deployed to ${DEPLOY_DIR}"

if [ -f "${DEPLOY_DIR}/.env" ]; then
  echo "Running migrations (if any)..."
  php "${DEPLOY_DIR}/bin/console" doctrine:migrations:migrate --no-interaction --env=prod
else
  echo "Skip migrations: ${DEPLOY_DIR}/.env not found" >&2
fi
