name: Bubble--Remove Branch Preview Apps

on:
  pull_request:
    types: [closed]
  workflow_dispatch:
    inputs:
      pr-number:
        require: true
        type: number

env:
  REPO_NAME_WITH_OWNER: ${{ github.repository }}
  REPO_NAME: ${{ github.event.repository.name }}

jobs:
  notify:
    name: Notify Pending Bubble Removal
    runs-on: ubuntu-latest

    steps:
      - name: Set Environment Variables for Closed PR
        run: |
          echo "PR_NUMBER=${{ github.event.number }}" >> $GITHUB_ENV
        if: ${{ !inputs.pr-number }}

      - name: Set Environment Variables for Bubble Destroy
        run: |
          echo "PR_NUMBER=${{ inputs.pr-number }}" >> $GITHUB_ENV
        if: ${{ inputs.pr-number }}

      - name: Add Removal Pending Message to Branch
        uses: hasura/comment-progress@v2.1.0
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          repository: ${{ github.repository }}
          number: ${{ env.PR_NUMBER }}
          id: destroy-preview
          message: "We'll work on going through all the bubbles in this branch and start popping 'em all! Once we're finished, most of the AWS resources provisioned for your preview apps on this pull request will be removed."

  delete:
    name: Remove Bubbles in Branch
    runs-on: ubuntu-latest

    env:
      AWS_ACCESS_KEY_ID: ${{ secrets.BUBBLE_AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.BUBBLE_AWS_SECRET_ACCESS_KEY }}
      AWS_REGION: ${{ secrets.AWS_REGION || 'us-east-1' }}

    steps:
      - name: Set Environment Variables for Closed PR
        run: |
          echo "PR_NUMBER=${{ github.event.number }}" >> $GITHUB_ENV
        if: ${{ !inputs.pr-number }}

      - name: Set Environment Variables for Bubble Destroy
        run: |
          echo "PR_NUMBER=${{ inputs.pr-number }}" >> $GITHUB_ENV
        if: ${{ inputs.pr-number }}

      - name: Missing AWS Credentials
        if: ${{ !env.AWS_SECRET_ACCESS_KEY && !env.AWS_ACCESS_KEY_ID }}
        run: exit 1
      - uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ env.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ env.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ env.AWS_REGION }}

      - name: Retrieve Commit Data from DynamoDB
        uses: mathiasvr/command-output@v1
        id: previewappdata
        with:
          run: |
            aws dynamodb get-item --table-name ${{ env.REPO_NAME }}-PreviewApps --key '{ "PullRequestId": {"N": "${{ env.PR_NUMBER }}"}}'

      - name: Parse Data to get AWS Resource IDs
        uses: satackey/action-js-inline@v0.0.2
        id: getbundles
        with:
          script: |
            const core = require('@actions/core')

            const pullRequestObj = ${{ steps.previewappdata.outputs.stdout }}
            const commitsArray = pullRequestObj.Item.Commits.L

            const bundles = []

            commitsArray.forEach(commit => {
              const bucketId = commit.M.BucketId.S
              const distro = commit.M.CloudFrontDistroId.S
              const lambdaPrefix = bucketId.split('-')[0]

              const command = `"gh workflow run bubble_remove_single_preview_app.yml -f bucket=${bucketId} -f distro=${distro} -f lambda=${lambdaPrefix} --repo ${{ env.REPO_NAME_WITH_OWNER }} -r main"`
              bundles.push(command)
            });

            core.setOutput('bundles', bundles.join("\n"))

      - name: Pop Bubble for Each Commit
        run: |
          myarray=(${{ steps.getbundles.outputs.bundles }})
          for (( i=0; i<=${#myarray[@]}; i++ )); do
            ${myarray[$i]}
          done
        env:
          GITHUB_TOKEN: ${{ secrets.BUBBLE_GITHUB_TOKEN }}

      - name: Soft Delete PR Data in DynamoDB
        run: |
          aws dynamodb update-item --table-name ${{ env.REPO_NAME }}-PreviewApps --key '{ "PullRequestId": {"N": "${{ env.PR_NUMBER }}"}}' --update-expression "SET IsActive = :val" --expression-attribute-values '{":val":{"BOOL":false}}' --return-values ALL_NEW
