#!/usr/bin/env bash
# Upload myoffice-publish.tar.gz to a Gitea Release on the public repo.
# Usage:
#   export GITEA_TOKEN='<token>'
#   ./proxmox/publish.sh --tar
#   ./proxmox/release.sh --gitea-url https://gitea.example.com --owner org --repo myoffice-public --tag v1.2.3
#
# Token needs write:repository on the public repo.

set -euo pipefail

script_dir="$(cd "$(dirname "$0")" && pwd)"
repo_root="$(cd "$script_dir/.." && pwd)"

gitea_url="${GITEA_URL:-}"
owner="${GITEA_OWNER:-}"
repo="${GITEA_REPO:-myoffice-public}"
tag="${TAG:-}"
token="${GITEA_TOKEN:-}"
asset_path="${ASSET_PATH:-}"
title="${TITLE:-}"
body="${BODY:-MyOffice published API + SPA (Proxmox CT artifact).}"
target="${TARGET:-main}"

usage() {
	echo "Usage: $0 --gitea-url URL --owner OWNER --tag TAG [--repo REPO] [--asset-path PATH]" >&2
	exit 1
}

while [[ $# -gt 0 ]]; do
	case "$1" in
		--gitea-url)
			gitea_url="$2"
			shift 2
			;;
		--owner)
			owner="$2"
			shift 2
			;;
		--repo)
			repo="$2"
			shift 2
			;;
		--tag)
			tag="$2"
			shift 2
			;;
		--asset-path)
			asset_path="$2"
			shift 2
			;;
		--title)
			title="$2"
			shift 2
			;;
		--body)
			body="$2"
			shift 2
			;;
		--target)
			target="$2"
			shift 2
			;;
		-h | --help)
			usage
			;;
		*)
			echo "Unknown argument: $1" >&2
			usage
			;;
	esac
done

if [[ -z "$token" ]]; then
	echo "GITEA_TOKEN (or export before run) is required." >&2
	exit 1
fi
if [[ -z "$gitea_url" || -z "$owner" || -z "$tag" ]]; then
	usage
fi

if [[ -z "$asset_path" ]]; then
	asset_path="$repo_root/myoffice-publish.tar.gz"
fi
if [[ ! -f "$asset_path" ]]; then
	echo "Asset not found: $asset_path — run ./proxmox/publish.sh --tar first." >&2
	exit 1
fi

gitea_url="${gitea_url%/}"
api="$gitea_url/api/v1"
asset_name="myoffice-publish.tar.gz"
if [[ -z "$title" ]]; then
	title="$tag"
fi

auth_header="Authorization: token $token"

api_call() {
	local method="$1"
	local uri="$2"
	local payload="${3:-}"
	if [[ -n "$payload" ]]; then
		curl -fsS -X "$method" -H "$auth_header" -H "Accept: application/json" \
			-H "Content-Type: application/json" -d "$payload" "$uri"
	else
		curl -fsS -X "$method" -H "$auth_header" -H "Accept: application/json" "$uri"
	fi
}

release_json=""
if release_json="$(api_call GET "$api/repos/$owner/$repo/releases/tags/$tag" 2>/dev/null)"; then
	release_id="$(python3 -c "import json,sys; print(json.load(sys.stdin)['id'])" <<<"$release_json")"
	echo "Release $tag already exists (id $release_id)."
else
	echo "Creating release $tag..."
	payload="$(TAG="$tag" TITLE="$title" BODY="$body" TARGET="$target" python3 <<'PY'
import json, os
print(json.dumps({
    "tag_name": os.environ["TAG"],
    "target_commitish": os.environ["TARGET"],
    "name": os.environ["TITLE"],
    "body": os.environ["BODY"],
    "draft": False,
    "prerelease": False,
}))
PY
)"
	release_json="$(api_call POST "$api/repos/$owner/$repo/releases" "$payload")"
	release_id="$(python3 -c "import json,sys; print(json.load(sys.stdin)['id'])" <<<"$release_json")"
	echo "Created release id $release_id."
fi

asset_ids="$(python3 -c "
import json, sys
data = json.load(sys.stdin)
for a in data.get('assets', []):
    if a.get('name') == '$asset_name':
        print(a['id'])
" <<<"$release_json")"

while IFS= read -r asset_id; do
	[[ -z "$asset_id" ]] && continue
	echo "Deleting existing asset id $asset_id ($asset_name)..."
	api_call DELETE "$api/repos/$owner/$repo/releases/$release_id/assets/$asset_id" >/dev/null || true
done <<<"$asset_ids"

upload_url="$api/repos/$owner/$repo/releases/$release_id/assets?name=$asset_name"
echo "Uploading $asset_path ..."
curl -fsS -X POST -H "$auth_header" -F "attachment=@$asset_path" "$upload_url"

download_url="$gitea_url/$owner/$repo/releases/download/$tag/$asset_name"
echo ""
echo "Uploaded. Download URL:"
echo "  $download_url"
echo "Latest API:"
echo "  $api/repos/$owner/$repo/releases/latest"
echo ""
