name: Cleanup Stale Hetzner Runners

on:
  schedule:
    # Run every hour to catch stuck runner VMs
    - cron: '0 * * * *'
  workflow_dispatch:
    inputs:
      max_age_minutes:
        description: 'Max age in minutes before a runner VM is destroyed'
        required: false
        default: '60'

jobs:
  cleanup:
    name: Cleanup Stale Runners
    runs-on: ubuntu-latest
    steps:
      - name: Install hcloud CLI
        run: |
          curl -sL https://github.com/hetznercloud/cli/releases/latest/download/hcloud-linux-amd64.tar.gz | tar xz
          sudo mv hcloud /usr/local/bin/

      - name: Cleanup stale runner VMs
        env:
          HCLOUD_TOKEN: ${{ '{{' }} secrets.HCLOUD_TOKEN {{ '}}' }}
        run: |
          MAX_AGE=${{ '{{' }} inputs.max_age_minutes || '60' {{ '}}' }}
          echo "Cleaning up runner VMs older than ${MAX_AGE} minutes..."

          SERVERS=$(hcloud server list --label managed-by=prisme --label purpose=ci-runner -o json 2>/dev/null || echo "[]")
          DESTROYED=0

          echo "$SERVERS" | jq -c '.[]' | while read -r server; do
            NAME=$(echo "$server" | jq -r '.name')
            ID=$(echo "$server" | jq -r '.id')
            CREATED=$(echo "$server" | jq -r '.created')

            # Calculate age in minutes
            CREATED_TS=$(date -d "$CREATED" +%s 2>/dev/null || date -j -f "%Y-%m-%dT%H:%M:%S" "$CREATED" +%s 2>/dev/null || echo 0)
            NOW_TS=$(date +%s)
            AGE_MIN=$(( (NOW_TS - CREATED_TS) / 60 ))

            if [ "$AGE_MIN" -gt "$MAX_AGE" ]; then
              echo "Destroying stale runner: $NAME (ID: $ID, age: ${AGE_MIN}m)"
              hcloud server delete "$ID" || true
              DESTROYED=$((DESTROYED + 1))
            else
              echo "Runner $NAME is ${AGE_MIN}m old (under ${MAX_AGE}m threshold), keeping."
            fi
          done

          echo "Cleanup complete. Destroyed $DESTROYED stale runner(s)."

      - name: Cleanup orphaned runner registrations
        env:
          GH_TOKEN: ${{ '{{' }} secrets.RUNNER_GITHUB_TOKEN {{ '}}' }}
        run: |
          echo "Checking for offline self-hosted runners..."
          RUNNERS=$(gh api repos/${{ '{{' }} github.repository {{ '}}' }}/actions/runners --jq '.runners[] | select(.status=="offline") | select(.name | startswith("prisme-runner-"))' 2>/dev/null || echo "")

          if [ -z "$RUNNERS" ]; then
            echo "No orphaned runners found."
            exit 0
          fi

          echo "$RUNNERS" | jq -c '.' | while read -r runner; do
            RUNNER_ID=$(echo "$runner" | jq -r '.id')
            RUNNER_NAME=$(echo "$runner" | jq -r '.name')
            echo "Removing offline runner registration: $RUNNER_NAME (ID: $RUNNER_ID)"
            gh api -X DELETE repos/${{ '{{' }} github.repository {{ '}}' }}/actions/runners/$RUNNER_ID || true
          done

          echo "Orphaned runner cleanup complete."
