# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0

# This workflow differs from PR CI in that it uploads a Docker build image to public ECR.
# This should be done only on push to main so that PRs from forks can successfully run CI
# since GitHub secrets cannot be shared with a PR from a fork.
name: CI on Branch `main`
on:
  workflow_dispatch:
  push:
    branches: [main]

# Allow only one Docker build image build to run at a time for the entire smithy-rs repo
concurrency:
  group: ci-main-yml
  cancel-in-progress: true

env:
  ecr_repository: public.ecr.aws/w0m4q9l7/github-awslabs-smithy-rs-ci

jobs:
  # Build and upload the Docker build image if necessary
  acquire-base-image:
    runs-on: smithy_ubuntu-latest_8-core
    name: Acquire Base Image
    timeout-minutes: 60
    outputs:
      docker-login-password: ${{ steps.set-token.outputs.docker-login-password }}
    permissions:
      id-token: write
      contents: read
    steps:
    - name: Checkout
      uses: actions/checkout@v4
    - name: Acquire credentials
      uses: aws-actions/configure-aws-credentials@v4
      with:
        role-to-assume: ${{ secrets.SMITHY_RS_PUBLIC_ECR_PUSH_ROLE_ARN }}
        role-session-name: GitHubActions
        aws-region: us-west-2
    - name: Save the docker login password to the output
      id: set-token
      run: |
        ENCRYPTED_PAYLOAD=$(
          gpg --symmetric --batch --passphrase "${{ secrets.DOCKER_LOGIN_TOKEN_PASSPHRASE }}" --output - <(aws ecr-public get-login-password --region us-east-1) | base64 -w0
        )
        echo "docker-login-password=$ENCRYPTED_PAYLOAD" >> $GITHUB_OUTPUT
    - name: Acquire base image
      id: acquire
      env:
        DOCKER_BUILDKIT: 1
        ENCRYPTED_DOCKER_PASSWORD: ${{ steps.set-token.outputs.docker-login-password }}
        DOCKER_LOGIN_TOKEN_PASSPHRASE: ${{ secrets.DOCKER_LOGIN_TOKEN_PASSPHRASE }}
      run: ./.github/scripts/acquire-build-image
    - name: Tag and upload image
      run: |
        IMAGE_TAG="$(./.github/scripts/docker-image-hash)"
        docker tag "smithy-rs-base-image:${IMAGE_TAG}" "${{ env.ecr_repository }}:${IMAGE_TAG}"
        docker tag "smithy-rs-base-image:${IMAGE_TAG}" "${{ env.ecr_repository }}:main"
        docker push "${{ env.ecr_repository }}:${IMAGE_TAG}"
        docker push "${{ env.ecr_repository }}:main"

  # Run the shared CI after a Docker build image has been uploaded to ECR
  ci:
    needs: acquire-base-image
    uses: ./.github/workflows/ci.yml
    with:
      run_sdk_examples: true
    secrets:
      ENCRYPTED_DOCKER_PASSWORD: ${{ needs.acquire-base-image.outputs.docker-login-password }}
      DOCKER_LOGIN_TOKEN_PASSPHRASE: ${{ secrets.DOCKER_LOGIN_TOKEN_PASSPHRASE }}
      CANARY_GITHUB_ACTIONS_ROLE_ARN: ${{ secrets.CANARY_GITHUB_ACTIONS_ROLE_ARN }}
      CANARY_STACK_CDK_OUTPUTS_BUCKET_NAME: ${{ secrets.CANARY_STACK_CDK_OUTPUTS_BUCKET_NAME }}
