# Creates an AWS AMI (system image) with compiled joystream-node and subkey
# 
name: Create AWS AMI

on:
  workflow_dispatch:

jobs:
  build:
    name: Build the code and run setup
    runs-on: ubuntu-latest
    env:
      STACK_NAME: create-joystream-node-ami-ga-${{ github.run_number }}
      KEY_NAME: joystream-github-action-key
    steps:
      - name: Extract branch name
        shell: bash
        run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
        id: extract_branch

      - name: Set AMI Name environment variable
        shell: bash
        run: echo "ami_name=joystream-node-${{ steps.extract_branch.outputs.branch }}-${{ github.run_number }}" >> $GITHUB_ENV
        id: ami_name

      - name: Checkout
        uses: actions/checkout@v2

      - name: Configure AWS credentials
        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: us-east-1

      - name: Deploy to AWS CloudFormation
        uses: aws-actions/aws-cloudformation-github-deploy@v1
        id: deploy_stack
        with:
          name: ${{ env.STACK_NAME }}
          template: devops/aws/cloudformation/single-instance.yml
          no-fail-on-empty-changeset: '1'
          parameter-overrides: 'KeyName=${{ env.KEY_NAME }}'

      - name: Install Ansible dependencies
        run: pipx inject ansible-core boto3 botocore

      - name: Run playbook
        uses: dawidd6/action-ansible-playbook@v2
        with:
          playbook: create-joystream-node-ami-playbook.yml
          directory: devops/aws
          requirements: requirements.yml
          key: ${{ secrets.SSH_PRIVATE_KEY }}
          inventory: |
            [all]
            ${{ steps.deploy_stack.outputs.PublicIp }}
          options: |
            --extra-vars "git_repo=https://github.com/${{ github.repository }} \
                          branch_name=${{ steps.extract_branch.outputs.branch }} instance_id=${{ steps.deploy_stack.outputs.InstanceId }}
                          ami_name=${{ env.ami_name }}"

      - name: Delete CloudFormation Stack
        if: always()
        continue-on-error: true
        run: |
          echo "Deleting ${{ env.STACK_NAME }} stack"
          aws cloudformation delete-stack --stack-name ${{ env.STACK_NAME }}
          echo "Waiting for ${{ env.STACK_NAME }} to be deleted..."
          aws cloudformation wait stack-delete-complete --stack-name ${{ env.STACK_NAME }}
