# ============================================================================
# DISABLED 3 August 2026 — this workflow will not run.
#
# Disabled via `gh workflow disable`, so the logic below is preserved verbatim.
# The disabled state lives in GitHub's API and is NOT visible in git.
#
# Re-enable with:
#   gh workflow enable "Preview: Cleanup Stale" --repo Gemma-Analytics/gemmbot
#
# Why: a daily 03:00 UTC cron sweeping for stale previews in a system whose
# deploy half had never run. It had fired 100+ times and found nothing to do,
# every night. Disabled together with preview-deploy.yml and preview-cleanup.yml
# so the three stay coherent — re-enable them as a set.
# ============================================================================
name: "Preview: Cleanup Stale"
run-name: "Preview: Cleanup Stale"

on:
  schedule:
    # Run daily at 3 AM UTC (4 AM Berlin time)
    - cron: '0 3 * * *'
  workflow_dispatch:

jobs:
  check-stale:
    runs-on: ubuntu-latest
    outputs:
      is_stale: ${{ steps.check.outputs.is_stale }}
    steps:
      - name: Check for stale preview environment
        id: check
        env:
          EC2_HOST: ${{ secrets.EC2_HOST }}
          EC2_USER: ${{ secrets.EC2_USER }}
          EC2_SSH_KEY: ${{ secrets.EC2_SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$EC2_SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H $EC2_HOST >> ~/.ssh/known_hosts

          # Check if preview exists and is older than 48h or has a dead process
          IS_STALE=$(ssh -i ~/.ssh/deploy_key $EC2_USER@$EC2_HOST '
            PREVIEW_DIR="/opt/gemmbot/preview"
            PR_FILE="${PREVIEW_DIR}/.pr-number"
            PID_FILE="${PREVIEW_DIR}/.pid"

            if [ ! -f "$PR_FILE" ] || [ ! -f "$PID_FILE" ]; then
              echo "false"
              exit 0
            fi

            PID=$(cat "$PID_FILE")
            if ! kill -0 "$PID" 2>/dev/null; then
              # Process is dead — stale
              echo "true"
              exit 0
            fi

            # Process is running — check age
            CREATED=$(stat -c %Y "$PR_FILE")
            NOW=$(date +%s)
            AGE_HOURS=$(( (NOW - CREATED) / 3600 ))
            if [ "$AGE_HOURS" -ge 48 ]; then
              echo "true"
            else
              echo "false"
            fi
          ')

          echo "is_stale=$IS_STALE" >> $GITHUB_OUTPUT
          if [ "$IS_STALE" = "true" ]; then
            echo "Found stale preview environment — will clean up"
          else
            echo "No stale preview environment found"
          fi

  cleanup-stale:
    needs: check-stale
    if: needs.check-stale.outputs.is_stale == 'true'
    uses: ./.github/workflows/preview-cleanup.yml
    secrets: inherit
