# #
#   @type               github workflow
#   @author             Aetherinox
#   @url                https://github.com/Aetherinox
#   @usage              cleans up the list of deployments in the environment history
#                       edit the 'environment:' to determine which deployment to keep clean
#                           - can be ran manually
#
#   @secrets            secrets.SELF_TOKEN                                          self github personal access token (fine-grained)
#                       secrets.SELF_TOKEN_CL                                       self github personal access token (classic)
#                       secrets.NPM_TOKEN                                           self npmjs access token
#                       secrets.PYPI_API_TOKEN                                      self Pypi API token (production site) - https://pypi.org/
#                       secrets.PYPI_API_TEST_TOKEN                                 self Pypi API token (test site) - https://test.pypi.org/
#                       secrets.SELF_DOCKERHUB_TOKEN                                self Dockerhub token
#                       secrets.ORG_TOKEN                                           org github personal access token (fine-grained)
#                       secrets.ORG_TOKEN_CL                                        org github personal access token (classic)
#                       secrets.ORG_DOCKERHUB_TOKEN                                 org dockerhub secret
#                       secrets.ORG_GITEA_TOKEN                                     org gitea personal access token (classic) with package:write permission
#                       secrets.BOT_GPG_KEY_ASC                                     bot gpg private key (armored) | BEGIN PGP PRIVATE KEY BLOCK
#                       secrets.BOT_GPG_PASSPHRASE                                  bot gpg private key passphrase
#                       secrets.DISCORD_WEBHOOK_CHAN_GITHUB_RELEASES                discord webhook to report release notifications from github to discord
#                       secrets.DISCORD_WEBHOOK_CHAN_GITHUB_WORKFLOWS               discord webhook to report workflow notifications from github to discord
#                       secrets.DISCORD_WEBHOOK_CHAN_GITHUB_UPDATES                 discord webhook to report activity notifications from github to discord
#
#
#   @local              these workflows can be tested locally through the use of `act`
#                           https://github.com/nektos/act
#                       Extract act to folder
#                       Add system env var with path to act.exe
#                       Run the commands:
#                           git pull https://github.com/username/repo
#                           act -W .github/workflows/deploy-clean.yml -P ubuntu-latest=catthehacker/ubuntu:full-22.04
#                           act -W .github/workflows/deploy-clean.yml -s TOKEN_CL=XXXXXXXXXX --pull=false
# #

# #

name: '🧹 Deployments › Clean'
run-name: '🧹 Deployments › Clean'

# #
#   triggers
# #

on:

    # #
    #   Trigger > Workflow Dispatch
    # #

    workflow_dispatch:
        inputs:

            # #
            #   Deployment Environment Name
            #
            #   this is the name of the deployment item
            # #

            DEPLOYMENT_ENV:
                description:    '📦 Deployment Environment'
                required:       true
                default:        'orion'
                type:           string

            # #
            #   Delay
            #
            #   Milliseconds to wait between cleaning up each action in history. Avoids secondary rate limit. Default: 500
            # #

            DEPLOYMENT_DELAY:
                description:    '🕛 Delete Delay'
                required:       true
                default:        '1000'
                type:           string

# #
#   environment variables
# #

env:
    DEPLOYMENT_ENV:             ${{ github.event.inputs.DEPLOYMENT_ENV || 'orion' }}
    DEPLOYMENT_DELAY:           ${{ github.event.inputs.DEPLOYMENT_DELAY || '1000' }}
    BOT_NAME_1:                 EuropaServ
    BOT_NAME_2:                 BinaryServ
    BOT_NAME_DEPENDABOT:        dependabot[bot]
    BOT_NAME_RENOVATE:          renovate[bot]

# #
#   jobs
# #

jobs:
    cleanup:
        name: >-
            🧹 Deployments › Clean
      # runs-on: ubuntu-latest
        runs-on: apollo-x64
        timeout-minutes: 5
        permissions: write-all

        steps:

            # #
            #   Cleanup › Set Env Variables
            # #

            - name: >-
                🕛 Get Timestamp
              id: task_cleanup_set_timestamp
              run: |
                  echo "YEAR=$(date +'%Y')" >> $GITHUB_ENV
                  echo "NOW=$(date +'%m-%d-%Y %H:%M:%S')" >> $GITHUB_ENV
                  echo "NOW_SHORT=$(date +'%m-%d-%Y')" >> $GITHUB_ENV
                  echo "NOW_LONG=$(date +'%m-%d-%Y %H:%M')" >> $GITHUB_ENV
                  echo "NOW_DOCKER_LABEL=$(date +'%Y%m%d')" >> $GITHUB_ENV

            # #
            #   Release › Github › Checkout › Arm64
            # #

            - name: >-
                ✅ Checkout
              id: task_cleanup_gh_checkout
              uses: actions/checkout@v4
              with:
                  fetch-depth: 0

            # #
            #   Cleanup › Start
            # #

            - name: >-
                ⚙️ Deployments › Clean
              id: task_cleanup_start
              uses: Aetherinox/delete-deploy-env-action@v3
              with:
                  token: ${{ secrets.SELF_TOKEN_CL }}
                  environment: '${{ env.DEPLOYMENT_ENV }}'
                  onlyRemoveDeployments: true
                  delay: "${{ env.DEPLOYMENT_DELAY }}"

            # #
            #   Cleanup › Get Weekly Commits
            # #

            - name: >-
                🕛 Get Weekly Commit List
              id: task_cleanup_set_weekly_commit_list
              run: |
                  echo 'WEEKLY_COMMITS<<EOF' >> $GITHUB_ENV
                  git log --format="[\`%h\`](${{ github.server_url }}/${{ github.repository }}/commit/%H) %s - %an" --since=7.days >> $GITHUB_ENV
                  echo 'EOF' >> $GITHUB_ENV


            # #
            #   Cleanup › Notify Github › Success
            # #

            - name: >-
                🔔 Send Discord Webhook Message (Success)
              id: task_cleanup_notify_discord_success
              uses: tsickert/discord-webhook@v7.0.0
              if: success()
              with:
                  username: 'Io'
                  avatar-url: 'https://i.imgur.com/8BVDkla.jpg'
                  webhook-url: ${{ secrets.DISCORD_WEBHOOK_CHAN_GITHUB_TVAPP2_WORKfLOWS }}
                  embed-title: "⚙️ ${{ github.workflow_ref }}"
                  embed-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
                  embed-thumbnail-url: 'https://i.imgur.com/zDIzE8T.jpg'
                  embed-description: |
                      ## 📦 ᲼Deployment Cleanup ᲼${{ job.status == 'success' && '✅' || '❌' }}

                      A **successful** deployment cleanup was triggered on your repository. The history for this environment has been wiped
                      and will no longer list previous deployments you've made.

                      - Environment: `${{ env.DEPLOYMENT_ENV }}`
                      - Cleanup Delay: `${{ env.DEPLOYMENT_DELAY }}`
                      - Workflow: `${{ github.workflow }} (#${{github.run_number}})`
                      - Runner: `${{ runner.name }}`
                      - Triggered By: `${{ github.actor }}`
                      - Status: `${{ job.status == 'success' && '✅ Successful' || '❌ Failed' }}`

                  embed-color: ${{ job.status == 'success' && '5763719' || '15418782' }}
                  embed-footer-text: "Completed at ${{ env.NOW }} UTC"
                  embed-timestamp: "${{ env.NOW_LONG }}"
                  embed-author-name: "${{ github.repository_owner }}"
                  embed-author-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
                  embed-author-icon-url: "https://avatars.githubusercontent.com/u/200161462"

            # #
            #   Cleanup › Notify Github › Failure
            # #

            - name: >-
                🔔 Send Discord Webhook Message (Failure)
              id: task_cleanup_notify_discord_failure
              uses: tsickert/discord-webhook@v7.0.0
              if: failure()
              with:
                  username: 'Io'
                  avatar-url: 'https://i.imgur.com/8BVDkla.jpg'
                  webhook-url: ${{ secrets.DISCORD_WEBHOOK_CHAN_GITHUB_TVAPP2_WORKfLOWS }}
                  embed-title: "⚙️ ${{ github.workflow_ref }}"
                  embed-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
                  embed-thumbnail-url: 'https://i.imgur.com/zDIzE8T.jpg'
                  embed-description: |
                      ## 📦 ᲼Deployment Cleanup ᲼${{ job.status == 'success' && '✅' || '❌' }}

                      A **failed** deployment cleanup was triggered on your repository. Since the action failed; no entries of your repo's
                      deployment history have been removed.

                      - Environment: `${{ env.DEPLOYMENT_ENV }}`
                      - Cleanup Delay: `${{ env.DEPLOYMENT_DELAY }}`
                      - Workflow: `${{ github.workflow }} (#${{github.run_number}})`
                      - Runner: `${{ runner.name }}`
                      - Triggered By: `${{ github.actor }}`
                      - Status: `${{ job.status == 'success' && '✅ Successful' || '❌ Failed' }}`

                  embed-color: ${{ job.status == 'success' && '5763719' || '15418782' }}
                  embed-footer-text: "Completed at ${{ env.NOW }} UTC"
                  embed-timestamp: "${{ env.NOW_LONG }}"
                  embed-author-name: "${{ github.repository_owner }}"
                  embed-author-url: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
                  embed-author-icon-url: "https://avatars.githubusercontent.com/u/200161462"

