name: Undeploy Preview from Cloud Run

on:
  pull_request:
    branches:
      - develop
    types:
      - closed

env:
  PROJECT_ID: metagame-thegame
  REGISTRY_REGION: us-east4
  REGISTRY_REPO: thegame
  CLOUDRUN_REGION: us-east4
  CLOUDSQL_CONNECTION_NAME: metagame-thegame:us-east4:thegame
  CLOUDSQL_INSTANCE_NAME: thegame

jobs:
  undeploy:
    name: Undeploy
    runs-on: ubuntu-latest

    steps:
      - name: Set up gcloud CLI
        uses: google-github-actions/setup-gcloud@v0.2.1
        with:
          project_id: ${{ env.PROJECT_ID }}
          service_account_key: ${{ secrets.GCP_SA_KEY }}
          export_default_credentials: true

      - name: Undeploy Backend
        run: gcloud -q run services delete backend-pr-${{ github.event.number }} --region ${CLOUDRUN_REGION}

      - name: Delete Backend Image
        run: gcloud -q artifacts docker images delete ${REGISTRY_REGION}-docker.pkg.dev/${PROJECT_ID}/${REGISTRY_REPO}/backend:pr-${{ github.event.number }}

      - name: Undeploy Hasura
        run: gcloud -q run services delete hasura-pr-${{ github.event.number }} --region ${CLOUDRUN_REGION}

      - name: Delete Hasura Image
        run: gcloud -q artifacts docker images delete ${REGISTRY_REGION}-docker.pkg.dev/${PROJECT_ID}/${REGISTRY_REPO}/hasura:pr-${{ github.event.number }}

      - name: Undeploy Frontend
        run: gcloud -q run services delete frontend-pr-${{ github.event.number }} --region ${CLOUDRUN_REGION}

      - name: Delete Frontend Image
        run: gcloud -q artifacts docker images delete ${REGISTRY_REGION}-docker.pkg.dev/${PROJECT_ID}/${REGISTRY_REPO}/frontend:pr-${{ github.event.number }}

      - name: Delete Database of Hasura
        run: |
          wget -q https://dl.google.com/cloudsql/cloud_sql_proxy.linux.amd64 -O cloud_sql_proxy
          chmod +x cloud_sql_proxy
          ./cloud_sql_proxy -instances ${CLOUDSQL_CONNECTION_NAME} -dir /tmp/cloudsql &
          PID=$!
          sleep 10
          PGPASSWORD=${{ secrets.GCP_POSTGRES_PASSWORD }} dropdb -h /tmp/cloudsql/${CLOUDSQL_CONNECTION_NAME} -U postgres hasura-pr-${{ github.event.number }} -f
          kill $PID

      - name: Delete Postgres User of Hasura
        run: |
          gcloud -q sql users delete hasura-pr-${{ github.event.number }} -i ${CLOUDSQL_INSTANCE_NAME}

      - name: Comment on Pull Request
        uses: thollander/actions-comment-pull-request@v1
        with:
          message: Successfully undeployed the Preview of this Pull Request
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
