#!/bin/bash
# Installs gitea-executor deb package from Gitea package registry.
#
# Usage:
#   ./install.sh <gitea-url> <owner> [version]
#
# Arguments can also be passed as environment variables:
#   GITEA_URL, OWNER, VERSION
#
# Optional GITEA_TOKEN: when set, sends Authorization on all curls (private package registry / CI).
#
# Examples:
#   ./install.sh https://gitea.example.com myorg
#   ./install.sh https://gitea.example.com myorg 2026.0405.120000
#   GITEA_URL=https://gitea.example.com OWNER=myorg ./install.sh

set -euo pipefail

CURL_HEADERS=()
[ -n "${GITEA_TOKEN:-}" ] && CURL_HEADERS+=(-H "Authorization: token ${GITEA_TOKEN}")

usage() {
    echo "Usage: install.sh <gitea-url> <owner> [version]"
    echo ""
    echo "  gitea-url   Gitea server URL (e.g. https://gitea.example.com)"
    echo "  owner       Package registry owner (user or organisation)"
    echo "  version     Version to install (default: latest available)"
    echo ""
    echo "Environment variables GITEA_URL, OWNER, VERSION can be used instead of positional arguments."
    exit 1
}

GITEA_URL="${GITEA_URL:-${1:-}}"
OWNER="${OWNER:-${2:-}}"
VERSION="${VERSION:-${3:-}}"

[ -z "${GITEA_URL}" ] && usage
[ -z "${OWNER}" ] && usage

if [ -z "${VERSION}" ]; then
    echo "Querying latest version of gitea-executor..."
    VERSION=$(curl -fsSL "${CURL_HEADERS[@]}" \
        "${GITEA_URL}/api/v1/packages/${OWNER}?type=generic&q=gitea-executor&limit=1&sort=newest" \
        | jq -r '.[0].version // empty')
    if [ -z "${VERSION}" ]; then
        echo "Error: could not determine latest version from ${GITEA_URL}" >&2
        exit 1
    fi
    echo "Latest version: ${VERSION}"
fi

DEB_FILE="gitea-executor_${VERSION}_amd64.deb"
DOWNLOAD_URL="${GITEA_URL}/api/packages/${OWNER}/generic/gitea-executor/${VERSION}/${DEB_FILE}"
TMP_DEB="/tmp/${DEB_FILE}"

echo "Downloading ${DEB_FILE}..."
curl -fsSL "${CURL_HEADERS[@]}" -o "${TMP_DEB}" "${DOWNLOAD_URL}"

echo "Installing gitea-executor ${VERSION}..."
dpkg -i "${TMP_DEB}"
rm -f "${TMP_DEB}"

echo ""
echo "gitea-executor ${VERSION} installed."
echo "  Binary:        /usr/local/bin/gitea-executor"
if command -v agent >/dev/null 2>&1; then
    echo "  Cursor agent:  already present"
else
    echo "  Cursor agent:  installed to /usr/local/bin/agent"
fi
