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

# Defaults (override via CLI flags)
GITEA_BASE_URL="https://git.motovaultpro.com"
TOKEN=""
OWNER="egullickson"
REPO="motovaultpro"
PER_PAGE=50

usage() {
  cat <<EOF
Usage:
  $0 --token=YOUR_TOKEN [--base-url=https://git.motovaultpro.com] [--owner=egullickson] [--repo=motovaultpro] [--per-page=50]

Examples:
  # Delete all Actions runs in egullickson/motovaultpro
  $0 --token=XXXX

  # Different repo
  $0 --token=XXXX --owner=someone --repo=otherrepo

  # Different server + page size
  $0 --token=XXXX --base-url=https://git.example.com --per-page=100
EOF
}

# --- CLI parsing ---
for arg in "$@"; do
  case "$arg" in
    --token=*) TOKEN="${arg#*=}" ;;
    --base-url=*) GITEA_BASE_URL="${arg#*=}" ;;
    --owner=*) OWNER="${arg#*=}" ;;
    --repo=*) REPO="${arg#*=}" ;;
    --per-page=*) PER_PAGE="${arg#*=}" ;;
    -h|--help) usage; exit 0 ;;
    *)
      echo "ERROR: Unknown argument: $arg"
      usage
      exit 1
      ;;
  esac
done

if [[ -z "$TOKEN" ]]; then
  echo "ERROR: --token= is required"
  usage
  exit 1
fi

# Basic validation
if ! [[ "$PER_PAGE" =~ ^[0-9]+$ ]]; then
  echo "ERROR: --per-page must be a number"
  exit 1
fi

api() {
  curl -fsS \
    -H "Authorization: token ${TOKEN}" \
    -H "Accept: application/json" \
    "$@"
}

page=1
deleted=0

while :; do
  echo "Fetching page ${page}..."
  json="$(api "${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${REPO}/actions/runs?limit=${PER_PAGE}&page=${page}")"

  # Try both common shapes:
  # - {"workflow_runs":[...]}
  # - {"runs":[...]}
  ids="$(echo "$json" | jq -r '(.workflow_runs // .runs // []) | .[].id')"

  if [[ -z "${ids}" ]]; then
    echo "No more runs found."
    break
  fi

  while read -r id; do
    [[ -z "$id" ]] && continue
    echo "Deleting run id=${id}"
    api -X DELETE "${GITEA_BASE_URL}/api/v1/repos/${OWNER}/${REPO}/actions/runs/${id}" >/dev/null
    deleted=$((deleted + 1))
  done <<< "${ids}"

  page=$((page + 1))
done

echo "Done. Deleted ${deleted} runs."
