name: Deployment
on: deployment
concurrency: ci-${{ github.event.deployment.environment }}
jobs:
  set-config:
    runs-on: ubuntu-latest
    timeout-minutes: 5
    outputs:
      awsAccount: ${{ steps[github.event.deployment.environment].outputs.awsAccount }}
      clusterName: ${{ steps[github.event.deployment.environment].outputs.clusterName }}
      nrLicenceSecretName: ${{ steps[github.event.deployment.environment].outputs.nrLicenceSecretName }}
      nrApiKeySecretName: ${{ steps[github.event.deployment.environment].outputs.nrApiKeySecretName }}
      accApiKeySecretName: ${{ steps[github.event.deployment.environment].outputs.accApiKeySecretName }}
      target: ${{ steps[github.event.deployment.task].outputs.target }}
      dark: ${{ steps[github.event.deployment.task].outputs.dark }}
      region: ${{ steps[github.event.deployment.task].outputs.region }}
      tfLockTimeout: ${{ steps[github.event.deployment.environment].outputs.tfLockTimeout }}
    steps:
      - id: info
        run: echo "${{ toJSON(github.event.deployment) }}"
      - id: dev
        if: github.event.deployment.environment == 'dev'
        run: |
          echo "awsAccount=632760434310" >> $GITHUB_OUTPUT
          echo "clusterName=falling-sea" >> $GITHUB_OUTPUT
          echo "nrLicenceSecretName=GLOBAL_NEWRELIC_DEV_LICENSE_KEY" >> $GITHUB_OUTPUT
          echo "nrApiKeySecretName=GLOBAL_NEWRELIC_DEV_PERSONAL_API_KEY" >> $GITHUB_OUTPUT
          echo "accApiKeySecretName=ACC_API_KEY_STAGE" >> $GITHUB_OUTPUT
          echo "tfLockTimeout=3500s" >> $GITHUB_OUTPUT
      - id: test
        if: github.event.deployment.environment == 'test'
        run: |
          echo "awsAccount=676116660762" >> $GITHUB_OUTPUT
          echo "clusterName=side-winder" >> $GITHUB_OUTPUT
          echo "nrLicenceSecretName=GLOBAL_NEWRELIC_TEST_LICENSE_KEY" >> $GITHUB_OUTPUT
          echo "nrApiKeySecretName=GLOBAL_NEWRELIC_TEST_PERSONAL_API_KEY" >> $GITHUB_OUTPUT
          echo "accApiKeySecretName=ACC_API_KEY_STAGE" >> $GITHUB_OUTPUT
          echo "tfLockTimeout=3500s" >> $GITHUB_OUTPUT
      - id: test-ci
        if: github.event.deployment.environment == 'test-ci'
        run: |
          echo "awsAccount=676116660762" >> $GITHUB_OUTPUT
          echo "clusterName=side-winder" >> $GITHUB_OUTPUT
          echo "nrLicenceSecretName=GLOBAL_NEWRELIC_TEST_LICENSE_KEY" >> $GITHUB_OUTPUT
          echo "nrApiKeySecretName=GLOBAL_NEWRELIC_TEST_PERSONAL_API_KEY" >> $GITHUB_OUTPUT
          echo "accApiKeySecretName=ACC_API_KEY_STAGE" >> $GITHUB_OUTPUT
          echo "tfLockTimeout=3500s" >> $GITHUB_OUTPUT
      - id: stage
        if: github.event.deployment.environment == 'stage'
        run: |
          echo "awsAccount=080865980379" >> $GITHUB_OUTPUT
          echo "clusterName=misty-sun" >> $GITHUB_OUTPUT
          echo "nrLicenceSecretName=GLOBAL_NEWRELIC_STAGE_LICENSE_KEY" >> $GITHUB_OUTPUT
          echo "nrApiKeySecretName=GLOBAL_NEWRELIC_STAGE_PERSONAL_API_KEY" >> $GITHUB_OUTPUT
          echo "accApiKeySecretName=ACC_API_KEY_STAGE" >> $GITHUB_OUTPUT
          echo "tfLockTimeout=3s" >> $GITHUB_OUTPUT
      - id: prod
        if: github.event.deployment.environment == 'prod'
        run: |
          echo "awsAccount=216399462328" >> $GITHUB_OUTPUT
          echo "clusterName=shiny-credit" >> $GITHUB_OUTPUT
          echo "nrLicenceSecretName=GLOBAL_NEWRELIC_PROD_LICENSE_KEY" >> $GITHUB_OUTPUT
          echo "nrApiKeySecretName=GLOBAL_NEWRELIC_PROD_PERSONAL_API_KEY" >> $GITHUB_OUTPUT
          echo "accApiKeySecretName=ACC_API_KEY_PROD" >> $GITHUB_OUTPUT
          echo "tfLockTimeout=3s" >> $GITHUB_OUTPUT
      - id: deploy
        if: github.event.deployment.task == 'deploy'
        run: |
          echo "target=all" >> $GITHUB_OUTPUT
          echo "dark=false" >> $GITHUB_OUTPUT
      - id: euc1-dark
        if: github.event.deployment.task == 'euc1-dark'
        run: |
          echo "target=module.dry-tf-poc_service_eu_central_1" >> $GITHUB_OUTPUT
          echo "region=euc1" >> $GITHUB_OUTPUT
          echo "dark=true" >> $GITHUB_OUTPUT
      - id: euc1
        if: github.event.deployment.task == 'euc1'
        run: |
          echo "target=module.dry-tf-poc_service_eu_central_1" >> $GITHUB_OUTPUT
          echo "region=euc1" >> $GITHUB_OUTPUT
          echo "dark=false" >> $GITHUB_OUTPUT
      - id: use1-dark
        if: github.event.deployment.task == 'use1-dark'
        run: |
          echo "target=module.dry-tf-poc_service_us_east_1" >> $GITHUB_OUTPUT
          echo "region=use1" >> $GITHUB_OUTPUT
          echo "dark=true" >> $GITHUB_OUTPUT
      - id: use1
        if: github.event.deployment.task == 'use1'
        run: |
          echo "target=module.dry-tf-poc_service_us_east_1" >> $GITHUB_OUTPUT
          echo "region=use1" >> $GITHUB_OUTPUT
          echo "dark=false" >> $GITHUB_OUTPUT
      - id: apn1-dark
        if: github.event.deployment.task == 'apn1-dark'
        run: |
          echo "target=module.dry-tf-poc_service_ap_northeast_1" >> $GITHUB_OUTPUT
          echo "region=apn1" >> $GITHUB_OUTPUT
          echo "dark=true" >> $GITHUB_OUTPUT
      - id: apn1
        if: github.event.deployment.task == 'apn1'
        run: |
          echo "target=module.dry-tf-poc_service_ap_northeast_1" >> $GITHUB_OUTPUT
          echo "region=apn1" >> $GITHUB_OUTPUT
          echo "dark=false" >> $GITHUB_OUTPUT
  count-running-deployments:
    runs-on: ubuntu-latest
    needs: set-config
    timeout-minutes: 5
    outputs:
      count: ${{ steps.parse-results.outputs.deployments }}
    steps:
      - name: configure environment aws credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-region: 'eu-central-1'
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          role-to-assume: arn:aws:iam::${{ needs.set-config.outputs.awsAccount }}:role/automation-gha-ci
      - uses: bbeesley/gha-check-for-running-deployments@main
        name: count eu-central-1 running deployments
        id: euc1
        with:
          region: eu-central-1
          application-name: dry-tf-poc-service-ecs-${{ github.event.deployment.environment }}
          deployment-group-name: dry-tf-poc-service-${{ github.event.deployment.environment }}
          deployment-status: InProgress
      - uses: bbeesley/gha-check-for-running-deployments@main
        name: count us-east-1 running deployments
        if: contains( 'stage,prod', github.event.deployment.environment ) || github.event.deployment.environment == 'test'
        id: use1
        with:
          region: us-east-1
          application-name: dry-tf-poc-service-ecs-${{ github.event.deployment.environment }}
          deployment-group-name: dry-tf-poc-service-${{ github.event.deployment.environment }}
          deployment-status: InProgress
      - uses: bbeesley/gha-check-for-running-deployments@main
        name: count ap-northeast-1 running deployments
        if: contains( 'stage,prod', github.event.deployment.environment )
        id: apn1
        with:
          region: ap-northeast-1
          application-name: dry-tf-poc-service-ecs-${{ github.event.deployment.environment }}
          deployment-group-name: dry-tf-poc-service-${{ github.event.deployment.environment }}
          deployment-status: InProgress
      - name: parse-results
        id: parse-results
        env:
          EUC1_COUNT: ${{ steps.euc1.outputs.deployments }}
          USE1_COUNT: ${{ steps.use1.outputs.deployments }}
          APN1_COUNT: ${{ steps.apn1.outputs.deployments }}
        run: |
          echo "deployments=$(expr ${EUC1_COUNT} + ${USE1_COUNT:-0} + ${APN1_COUNT:-0})" >> $GITHUB_OUTPUT
  deploy:
    name: 'deploy ref ${{ github.event.deployment.ref }} to ${{ github.event.deployment.environment }}'
    if: github.actor != 'dependabot[bot]' && needs.count-running-deployments.outputs.deployments == 0
    needs: [set-config, count-running-deployments]
    uses: ./.github/workflows/common-tf-apply.yml
    with:
      environment: ${{ github.event.deployment.environment }}
      ref: ${{ github.event.deployment.ref }}
      task: ${{ github.event.deployment.task }}
      nodeVersion: '16.17.0'
      tfVersion: '0.14.11'
      awsDefaultRegion: 'eu-central-1'
      awsAccount: ${{ needs.set-config.outputs.awsAccount }}
      dark: ${{ needs.set-config.outputs.dark }}
      target: ${{ needs.set-config.outputs.target }}
      tfLockTimeout: ${{ needs.set-config.outputs.tfLockTimeout }}
      regionShortName: ${{ needs.set-config.outputs.region }} 
    secrets:
      AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
      AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
      TEAM_GITHUB_TOKEN: ${{ secrets.TEAM_GITHUB_TOKEN }}
      PD_NR_INTEGRATION_KEY: ${{ secrets.PD_NR_INTEGRATION_KEY }}
      GLOBAL_JFROG_ARTIFACTORY_TOKEN: ${{ secrets.GLOBAL_JFROG_ARTIFACTORY_TOKEN }}
      NEWRELIC_LICENCE_KEY: ${{ secrets[needs.set-config.outputs.nrLicenceSecretName] }}
      NEWRELIC_API_KEY: ${{ secrets[needs.set-config.outputs.nrApiKeySecretName] }}
      ACC_API_KEY: ${{ secrets[needs.set-config.outputs.accApiKeySecretName] }}
  post-deploy-tasks:
    runs-on: ubuntu-latest
    if: github.actor != 'dependabot[bot]' && needs.count-running-deployments.outputs.deployments == 0
    needs:
      - set-config
      - deploy
    timeout-minutes: 10
    env:
      AWS_DEFAULT_REGION: 'eu-central-1'
      SOME_TEAMS_CHANNEL_WEBHOOK: https://performgroup.webhook.office.com/webhookb2/ddb64741-8e33-4bc2-9479-b01aec2ff40e@30459df5-1e53-4d8b-a162-0ad2348546f1/IncomingWebhook/6ccbbef06f954b9abdbefa4d8424c3ae/a91bd9c3-d9cc-4df8-86b8-ca912552c423
    steps:
      - uses: actions/checkout@v3.3.0
        with:
          fetch-depth: 0
          ref: ${{ github.event.deployment.ref }}
      - uses: actions/setup-node@v3
        with:
          node-version: '16.17.0'
      - name: configure environment aws credentials
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-region: 'eu-central-1'
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          role-to-assume: arn:aws:iam::${{ needs.set-config.outputs.awsAccount }}:role/automation-gha-ci
      - name: npm auth
        env:
          JFROG_ARTIFACTORY_TOKEN: ${{ secrets.GLOBAL_JFROG_ARTIFACTORY_TOKEN }}
        run: |
          echo "//npm.companyxplatform.com/:_authToken=$JFROG_ARTIFACTORY_TOKEN" >> .npmrc
          cp .npmrc ~/
      - name: register service in dry-tf-poc-router - ${{ github.event.deployment.environment }}
        if: github.event.deployment.task == 'deploy' && github.event.deployment.environment != 'test-ci'
        run: npx @companyx/atl-register-service -s ${{ github.event.deployment.environment }}
      - name: update-alarm-notifier-config-${{ github.event.deployment.environment }}-euc1
        if: contains( 'dev,stage,prod', github.event.deployment.environment ) || github.event.deployment.environment == 'test'
        run: |
          aws dynamodb put-item \
          --table-name $(aws cloudformation list-exports --region eu-central-1 --query 'Exports[?Name==`alarm-notifier-${{ github.event.deployment.environment }}-config-table`].Value' --output text) \
          --region eu-central-1 \
          --item \
          '{
          "service": {"S":"${{ github.event.repository.name }}"},
          "pagerDutyIntegrationKey": {"S":"${{ secrets.PAGERDUTY_INTEGRATION_KEY }}"},
          "teamsWebhookUrl": {"S":"${{ env.SOME_TEAMS_CHANNEL_WEBHOOK }}"}
          }'
      - name: update-alarm-notifier-config-${{ github.event.deployment.environment }}-use1
        if: contains( 'stage,prod', github.event.deployment.environment ) || github.event.deployment.environment == 'test'
        run: |
          aws dynamodb put-item \
          --table-name $(aws cloudformation list-exports --region us-east-1 --query 'Exports[?Name==`alarm-notifier-${{ github.event.deployment.environment }}-config-table`].Value' --output text) \
          --region us-east-1 \
          --item \
          '{
          "service": {"S":"${{ github.event.repository.name }}"},
          "pagerDutyIntegrationKey": {"S":"${{ secrets.PAGERDUTY_INTEGRATION_KEY }}"},
          "teamsWebhookUrl": {"S":"${{ env.SOME_TEAMS_CHANNEL_WEBHOOK }}"}
          }'
      - name: update-alarm-notifier-config-${{ github.event.deployment.environment }}-apn1
        if: contains( 'stage,prod', github.event.deployment.environment )
        run: |
          aws dynamodb put-item \
          --table-name $(aws cloudformation list-exports --region us-east-1 --query 'Exports[?Name==`alarm-notifier-${{ github.event.deployment.environment }}-config-table`].Value' --output text) \
          --region us-east-1 \
          --item \
          '{
          "service": {"S":"${{ github.event.repository.name }}"},
          "pagerDutyIntegrationKey": {"S":"${{ secrets.PAGERDUTY_INTEGRATION_KEY }}"},
          "teamsWebhookUrl": {"S":"${{ env.SOME_TEAMS_CHANNEL_WEBHOOK }}"}
          }'
      - name: ECS Auto Scaling Check (dev)
        if: contains(fromJSON('["dev"]'), github.event.deployment.environment )
        run: |
          npx @companyx/atl-ecs-scaling-check \
          -r eu-central-1:service/${{ needs.set-config.outputs.clusterName }}-eu-central-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }}
      - name: ECS Auto Scaling Check (test)
        if: contains(fromJSON('["test"]'), github.event.deployment.environment )
        run: |
          npx @companyx/atl-ecs-scaling-check \
          -r us-east-1:service/${{ needs.set-config.outputs.clusterName }}-us-east-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }} \
          -r eu-central-1:service/${{ needs.set-config.outputs.clusterName }}-eu-central-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }}
      - name: ECS Auto Scaling Check (stage / prod)
        if: contains(fromJSON('["prod","stage"]'), github.event.deployment.environment )
        run: |
          npx @companyx/atl-ecs-scaling-check \
          -r us-east-1:service/${{ needs.set-config.outputs.clusterName }}-us-east-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }} \
          -r eu-central-1:service/${{ needs.set-config.outputs.clusterName }}-eu-central-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }} \
          -r ap-northeast-1:service/${{ needs.set-config.outputs.clusterName }}-ap-northeast-1-fargate/dry-tf-poc-service-${{ github.event.deployment.environment }}
      - name: mark deployment as successful
        if: ${{ success() }}
        run: |
          curl -X POST https://api.github.com/repos/${{ github.repository }}/deployments/${{ github.event.deployment.id }}/statuses \
          -u ${{ secrets.TEAM_GITHUB_TOKEN }} \
          --data '{"state": "success", "environment": "${{ github.event.deployment.environment }}", "description": "Completed deployment of ${{ github.event.deployment.ref }} to ${{ github.event.deployment.environment }}"}'
      - name: mark deployment as failed
        if: ${{ failure() }}
        run: |
          curl -X POST https://api.github.com/repos/${{ github.repository }}/deployments/${{ github.event.deployment.id }}/statuses \
          -u ${{ secrets.TEAM_GITHUB_TOKEN }} \
          --data '{"state": "failure", "environment": "${{ github.event.deployment.environment }}", "description": "Failed deployment of ${{ github.event.deployment.ref }} to ${{ github.event.deployment.environment }}"}'
      - name: mark deployment as cancelled
        if: ${{ cancelled() }}
        run: |
          curl -X POST https://api.github.com/repos/${{ github.repository }}/deployments/${{ github.event.deployment.id }}/statuses \
          -u ${{ secrets.TEAM_GITHUB_TOKEN }} \
          --data '{"state": "failure", "environment": "${{ github.event.deployment.environment }}", "description": "Cancelled deployment of ${{ github.event.deployment.ref }} to ${{ github.event.deployment.environment }}"}'
  lexi:
    name: notify lexi
    runs-on: ubuntu-latest
    needs: post-deploy-tasks
    timeout-minutes: 5
    if: github.event.deployment.environment != 'test-ci'
    steps:
      - uses: actions/checkout@v3.3.0
        with:
          fetch-depth: 0
          ref: ${{ github.event.deployment.ref }}
      - uses: actions/checkout@v3.3.0
        with:
          repository: getncompanyx/facilitate-drone-github-action
          token: ${{ secrets.GLOBAL_GITHUB_TOKEN }}
          path: .getncompanyx/facilitate-drone-github-action
      - name: Facilitate Drone
        uses: ./.getncompanyx/facilitate-drone-github-action
      - name: lexi
        uses: docker://nzad/drone-lexi:2
        env:
          LEXI_TOKEN: ${{ SECRETS.GLOBAL_LEXI_TOKEN }}
          PLUGIN_ENV: ${{ github.event.deployment.environment }}
          PLUGIN_REGION: eu-central-1
  upload-open-api-spec:
    name: upload open api spec
    runs-on: ubuntu-latest
    needs: post-deploy-tasks
    timeout-minutes: 5
    if: github.event.deployment.environment == 'prod' || github.event.deployment.environment == 'stage' || github.event.deployment.environment == 'test'
    container:
      image: docker://707907454361.dkr.ecr.eu-central-1.amazonaws.com/openapi-publish-plugin:latest
      credentials:
        username: AWS
        password: ${{ secrets.GLOBAL_ECR_707907454361_DKR_ECR_EU_CENTRAL_1_AMAZONAWS_COM_PASSWORD }}
    steps:
      - uses: actions/checkout@v3.3.0
        with:
          fetch-depth: 0
          ref: ${{ github.event.deployment.ref }}
      - name: upload open api docs
        env:
          PLUGIN_API_SPEC_FILE_PATH: ./open-api.yml
          PLUGIN_API_ENV: ${{ github.event.deployment.environment }}
          PLUGIN_API_TITLE: "dry-tf-poc API"
          AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
          AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          AWS_DEFAULT_REGION: eu-central-1
        run: |
          publishApiSpec
