name: Deploy terraform stack

on:
  push:
    branches:
      - dev
      - prod

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v2

      - name: Setup AWS credentials file
        run: |
          mkdir -p ~/.aws
          echo "[DevAdmin]" > ~/.aws/credentials
          echo "aws_access_key_id = ${{ secrets.DEV_AWS_ACCESS_KEY_ID }}" >> ~/.aws/credentials
          echo "aws_secret_access_key = ${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }}" >> ~/.aws/credentials
          echo "[ProdAdmin]" >> ~/.aws/credentials
          echo "aws_access_key_id = ${{ secrets.PROD_AWS_ACCESS_KEY_ID }}" >> ~/.aws/credentials
          echo "aws_secret_access_key = ${{ secrets.PROD_AWS_SECRET_ACCESS_KEY }}" >> ~/.aws/credentials

      - name: Setup AWS config file
        run: |
          echo "[profile DevAdmin]" > ~/.aws/config
          echo "region = eu-west-2" >> ~/.aws/config
          echo "[profile ProdAdmin]" >> ~/.aws/config
          echo "region = eu-west-2" >> ~/.aws/config

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v1
        with:
          terraform_version: 1.5.2

      - name: Configure AWS credentials (DevAdmin)
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.DEV_AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.DEV_AWS_SECRET_ACCESS_KEY }}
          aws-region: eu-west-2
        env:
          AWS_PROFILE: "DevAdmin"

      - name: Terraform Init
        run: cd infrastructure/terraform && terraform init

      - name: Terraform Workspace
        run: |
          BRANCH_NAME=$(echo "${{ github.ref }}" | sed -e "s/^refs\/heads\///")
          cd infrastructure/terraform
          terraform workspace select ${BRANCH_NAME} || terraform workspace new ${BRANCH_NAME}

      - name: Terraform Plan
        run: |
          BRANCH_NAME=$(echo "${{ github.ref }}" | sed -e "s/^refs\/heads\///")
          cd infrastructure/terraform && terraform plan -var-file=${BRANCH_NAME}.tfvars

      - name: Deploy to Dev
        if: github.ref == 'refs/heads/dev'
        run: cd infrastructure/terraform && terraform apply -var-file=dev.tfvars -auto-approve
        env:
          name: dev

      - name: Configure AWS credentials (ProdAdmin)
        uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.PROD_AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.PROD_AWS_SECRET_ACCESS_KEY }}
          aws-region: eu-west-2
        env:
          AWS_PROFILE: "ProdAdmin"

      - name: Deploy to Prod
        if: github.ref == 'refs/heads/prod'
        run: cd infrastructure/terraform && terraform apply -var-file=prod.tfvars -auto-approve
        env:
          name: prod
