#!/usr/bin/env bash
set -e

# Change to repo root
cd "$(dirname "$0")"

# Check if FORGEJO_TOKEN is set
if [ -z "$FORGEJO_TOKEN" ]; then
  echo "Error: FORGEJO_TOKEN is not set"
  echo "Please set it with: export FORGEJO_TOKEN='your-token-here'"
  exit 1
fi

OWNER="geomind_code"

# Get version from latest tag or use 'dev'
VERSION=$(git describe --tags --abbrev=0 2>/dev/null || echo "dev")
echo "Using version: $VERSION"

# Verify token works
echo "Verifying token..."
if ! curl -sf -H "Authorization: token $FORGEJO_TOKEN" "https://forge.ourworld.tf/api/v1/user" > /dev/null; then
  echo "Error: FORGEJO_TOKEN is invalid or expired"
  exit 1
fi
echo "Token verified"

# Check for forgejo-runner and install if needed
if ! command -v forgejo-runner &> /dev/null; then
  echo "Installing forgejo-runner..."
  curl -sSL https://forge.ourworld.tf/api/packages/lhumina_research/generic/forgejo-runner/dev/install.sh | bash
else
  echo "forgejo-runner already installed"
fi

# Detect OS and run appropriate workflow
if [[ "$(uname)" == "Darwin" ]]; then
  echo "Running macOS build workflow..."
  forgejo-runner exec \
    -j build-macos \
    -s FORGEJO_TOKEN="$FORGEJO_TOKEN" \
    --forgejo-instance "https://forge.ourworld.tf" \
    --env VERSION="$VERSION" \
    --env OWNER="$OWNER" \
    -i "-self-hosted" \
    -W .forgejo/workflows/build-macos.yaml
elif [[ "$(uname)" == "Linux" ]]; then
  echo "Running Linux build workflow..."
  forgejo-runner exec \
    -j build-linux \
    -s FORGEJO_TOKEN="$FORGEJO_TOKEN" \
    --forgejo-instance "https://forge.ourworld.tf" \
    --env VERSION="$VERSION" \
    --env OWNER="$OWNER" \
    -i "-self-hosted" \
    -W .forgejo/workflows/build-linux.yaml
else
  echo "Unsupported OS: $(uname)"
  exit 1
fi

echo ""
echo "Local build complete. Pushing to remote..."
echo ""
