#!/bin/bash
set -e
if [ "$EUID" -ne 0 ]; then echo "❌ Run as root." >&2; exit 1; fi

echo "🔎 Fetching latest Gitea version from GitHub API..."
LATEST_VERSION=$(curl -s https://api.github.com/repos/go-gitea/gitea/releases/latest | grep -Po '"tag_name": "v\K[0-9.]+')

if [ -z "$LATEST_VERSION" ]; then
    echo "❌ ERROR: Could not determine latest Gitea version. Check network access to api.github.com." >&2
    exit 1
fi
echo "✅ Found latest version: $LATEST_VERSION"

echo "🛑 Stopping Gitea service before update..."
# Stop the service if the binary exists, otherwise ignore error
[ -f /usr/local/bin/gitea ] && systemctl stop gitea || true

echo "🔽 Downloading Gitea binary version $LATEST_VERSION..."
wget -q --show-progress -O /usr/local/bin/gitea "https://dl.gitea.io/gitea/${LATEST_VERSION}/gitea-${LATEST_VERSION}-linux-amd64"

echo "🔧 Setting permissions..."
chmod +x /usr/local/bin/gitea

echo "🚀 Starting Gitea service..."
systemctl daemon-reload
systemctl start gitea
echo "✅ Gitea update complete."