---
#################################
#################################
## Deploy Docker Image Release ##
#################################
#################################

#
# Documentation:
# https://help.github.com/en/articles/workflow-syntax-for-github-actions
#
name: Deploy Release
###########################################
# Start the job upon publishing a release #
###########################################
on:
  # Start when a release is published
  release:
    types: [published]
  workflow_dispatch:
    # Set the input variables you want to pull in
    inputs:
      release_version:
        description: 'version to release. Ex: v4.3.2'
        required: true
        default: 'v'

###############
# Set the Job #
###############
jobs:
  build:
    # Name the Job
    name: Deploy Docker Image - Release
    # Set the agent to run on
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        images:
          - container-build-target: final_slim
            container-image-id-prefix: slim-
            deployment-environment-identifier: Release-SLIM
            image-id: slim
          - container-build-target: final_standard
            container-image-id-prefix: ""
            deployment-environment-identifier: Release
            image-id: standard
    timeout-minutes: 60

    ###############
    # Steps below #
    ###############
    steps:
      ############################
      # Checkout the source code #
      ############################
      - name: Checkout Code
        uses: actions/checkout@v3

      ###########################
      # Set current date to ENV #
      ###########################
      - name: Get current date
        run: |
          echo "Appending the build date contents to GITHUB_ENV..."
          echo "BUILD_DATE=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" >> "${GITHUB_ENV}"

      #######################
      # Setup Docker BuildX #
      #######################
      - name: Setup BuildX
        uses: docker/setup-buildx-action@v2.0.0

      ######################
      # Login to DockerHub #
      ######################
      - name: Login to DockerHub
        uses: docker/login-action@v2.0.0
        with:
          username: ${{ secrets.DOCKER_USERNAME }}
          password: ${{ secrets.DOCKER_PASSWORD }}

      ####################
      # Login to GHCR.io #
      ####################
      - name: Login to GitHub Container Registry
        uses: docker/login-action@v2.0.0
        with:
          registry: ghcr.io
          username: ${{ secrets.GCR_USERNAME }}
          password: ${{ secrets.GCR_TOKEN }}

      ###########################
      # Get the current release #
      ###########################
      - name: Get current Release number
        # shellcheck disable=SC2062
        run: |
          echo "RELEASE_VERSION=$(echo ${{ github.event.release.name }} \
          | grep -E -o "v[[:digit:]]+\.[[:digit:]]+\.[[:digit:]]+")" \
          >> "${GITHUB_ENV}"
          if [ -z "${RELEASE_VERSION}" ]; then
            echo "No release version found in environment, using input..."
            echo "RELEASE_VERSION=${{ github.event.inputs.release_version }}" \
            >> "${GITHUB_ENV}"
          fi

      #########################
      # Update deployment API #
      #########################
      - name: Start deployment
        uses: bobheadxi/deployments@v1.3.0
        id: deployment
        with:
          step: start
          token: ${{ secrets.GITHUB_TOKEN }}
          env: ${{ matrix.images.deployment-environment-identifier }}

      ######################################
      # Build the docker image and push it #
      ######################################
      - name: Build Docker image - ${{ matrix.images.image-id }}
        uses: docker/build-push-action@v3.1.0
        with:
          context: .
          file: ./Dockerfile
          build-args: |
            BUILD_DATE=${{ env.BUILD_DATE }}
            BUILD_REVISION=${{ github.sha }}
            BUILD_VERSION=${{ github.sha }}
          load: false
          push: true
          tags: |
            github/super-linter:${{ matrix.images.container-image-id-prefix }}latest
            github/super-linter:${{ matrix.images.container-image-id-prefix }}v4
            github/super-linter:${{ matrix.images.container-image-id-prefix }}${{ env.RELEASE_VERSION }}
            ghcr.io/github/super-linter:${{ matrix.images.container-image-id-prefix }}latest
            ghcr.io/github/super-linter:${{ matrix.images.container-image-id-prefix }}v4
            ghcr.io/github/super-linter:${{ matrix.images.container-image-id-prefix }}${{ env.RELEASE_VERSION }}
          target: "${{ matrix.images.container-build-target }}"

      #########################
      # Update Deployment API #
      #########################
      - name: Update deployment status
        uses: bobheadxi/deployments@v1.3.0
        if: always()
        with:
          step: finish
          token: ${{ secrets.GITHUB_TOKEN }}
          status: ${{ job.status }}
          deployment_id: ${{ steps.deployment.outputs.deployment_id }}
          env: ${{ steps.deployment.outputs.env }}
          env_url: https://github.com/github/super-linter/releases/tag/${{ env.RELEASE_VERSION }}

      #######################################################
      # Create a GitHub Issue with the info from this build #
      #######################################################
      - name: Create GitHub Issue for failure
        if: failure()
        uses: actions/github-script@v6
        id: create-issue
        with:
          # https://octokit.github.io/rest.js/v18#issues-create
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            const create = await github.rest.issues.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: "Failed to deploy release to production",
              body: "Automation has failed us! Failed to push release ${{ env.RELEASE_VERSION }}\nMore information can be found at:\n - ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}"
            })
            console.log('create', create)
            return create.data.number

      ############################
      # Assign admins on failure #
      ############################
      - name: Assign Admins on failure
        uses: actions/github-script@v6
        if: failure()
        with:
          # https://octokit.github.io/rest.js/v18#issues-create
          github-token: ${{secrets.GITHUB_TOKEN}}
          script: |
            github.rest.issues.addAssignees({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: "${{ steps.create-issue.outputs.result }}",
              assignees: [
                'admiralawkbar',
                'lindluni',
                'IAmHughes',
                'nemchik',
                'Hanse00',
                'GaboFDC',
                'ferrarimarco'
              ]
            })