# This GitHub Actions workflow runs on manual trigger on a branch of a
# repository, and configures the React app in the AWS Amplify Console.
#
# First, the GitHub Action deploys the 'stack.yaml' AWS CloudFormation stack
# to your AWS Account. This stack configures the React app in the AWS Amplify Console.
#
# Then, you need to trigger a first build in the AWS Amplify Console to
# fully configure it.

on:
  workflow_dispatch:
    inputs:
      region:
        description: 'AWS Region to deploy to'
        required: true
        default: 'us-east-1'

name: Manual Deploy

jobs:
  # Deploy the React app to AWS Amplify Console.
  # This job will run on every code change to the master branch, but will only deploy
  # changes if the infrastructure CloudFormation template in the repository changes.
  amplify:
    name: Deploy to Amplify Console
    runs-on: ubuntu-latest
    outputs:
      env-name: ${{ steps.env-name.outputs.environment }}
    steps:
    - name: Checkout
      uses: actions/checkout@v2

    - name: Configure AWS credentials
      id: creds
      uses: aws-actions/configure-aws-credentials@v1
      with:
        aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
        aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
        aws-region: ${{ github.event.inputs.region}}

    - name: Configure environment name
      id: env-name
      env:
        REPO: ${{ github.repository }}
      run: |
        ENVIRONMENT=`echo $REPO | tr "/" "-"`
        echo "Environment name: $ENVIRONMENT"
        echo "::set-output name=environment::$ENVIRONMENT"

    - name: Deploy to Amplify Console with CloudFormation
      id: amplify-stack
      uses: aws-actions/aws-cloudformation-github-deploy@v1
      with:
        name: ${{ steps.env-name.outputs.environment }}
        template: stack.yaml
        no-fail-on-empty-changeset: "1"
        parameter-overrides: >-
          Name=${{ steps.env-name.outputs.environment }},
          Repository=https://github.com/${{ github.repository }},
          OauthToken=${{ secrets.AMPLIFY_TOKEN }},
          Domain=${{secrets.AMPLIFY_DOMAIN}}
    # When a domain is configured to the stack,
    # it gets configured in the environment and printed to the console.
    - name: Print default domain
      env:
        DefaultDomain: ${{ steps.amplify-stack.outputs.DefaultDomain }}
      run: |
        echo "Default Domain: $DefaultDomain"
