name: pr-cleanup
on:
  pull_request:
    types: closed
  workflow_dispatch:
    inputs:
      pr_number:
        description: "PR number"
        required: true

permissions:
  packages: write

jobs:
  cleanup:
    runs-on: "ubuntu-latest"
    steps:
      - name: Get PR number
        id: pr_number
        run: |
          if [ -n "${{ github.event.pull_request.number }}" ]; then
            echo "PR_NUMBER=${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
          else
            echo "PR_NUMBER=${{ github.event.inputs.pr_number }}" >> $GITHUB_OUTPUT
          fi

      - name: Delete image
        continue-on-error: true
        uses: bots-house/ghcr-delete-image-action@v1.1.0
        with:
          owner: coder
          name: coder-preview
          token: ${{ secrets.GITHUB_TOKEN }}
          tag: pr${{ steps.pr_number.outputs.PR_NUMBER }}

      - name: Set up kubeconfig
        run: |
          set -euo pipefail
          mkdir -p ~/.kube
          echo "${{ secrets.PR_DEPLOYMENTS_KUBECONFIG }}" > ~/.kube/config
          export KUBECONFIG=~/.kube/config

      - name: Delete helm release
        run: |
          set -euo pipefail
          helm delete --namespace "pr${{ steps.pr_number.outputs.PR_NUMBER }}" "pr${{ steps.pr_number.outputs.PR_NUMBER }}" || echo "helm release not found"

      - name: "Remove PR namespace"
        run: |
          kubectl delete namespace "pr${{ steps.pr_number.outputs.PR_NUMBER }}" || echo "namespace not found"

      - name: "Remove DNS records"
        run: |
          set -euo pipefail
          # Get identifier for the record
          record_id=$(curl -X GET "https://api.cloudflare.com/client/v4/zones/${{ secrets.PR_DEPLOYMENTS_ZONE_ID }}/dns_records?name=%2A.pr${{ steps.pr_number.outputs.PR_NUMBER }}.${{ secrets.PR_DEPLOYMENTS_DOMAIN }}" \
          -H "Authorization: Bearer ${{ secrets.PR_DEPLOYMENTS_CLOUDFLARE_API_TOKEN }}" \
          -H "Content-Type:application/json" | jq -r '.result[0].id') || echo "DNS record not found"

          echo "::add-mask::$record_id"

          # Delete the record
          (
            curl -X DELETE "https://api.cloudflare.com/client/v4/zones/${{ secrets.PR_DEPLOYMENTS_ZONE_ID }}/dns_records/$record_id" \
            -H "Authorization: Bearer ${{ secrets.PR_DEPLOYMENTS_CLOUDFLARE_API_TOKEN }}" \
            -H "Content-Type:application/json" | jq -r '.success'
          ) || echo "DNS record not found"

      - name: "Delete certificate"
        if: ${{ github.event.pull_request.merged == true }}
        run: |
          set -euxo pipefail
          kubectl delete certificate "pr${{ steps.pr_number.outputs.PR_NUMBER }}-tls" -n pr-deployment-certs || echo "certificate not found"
