name: Create AMI from firmware image in S3 bucket

inputs:
  firmware_image_name:
    description: Name of the firmware image
    required: true
  firmware_image_s3_bucket:
    description: Name of the S3 bucket where the image resides
    required: true

runs:
  using: "composite"
  steps:
    - name: Import snapshot based on firmware image
      id: import_snapshot
      shell: bash
      run: |
        echo "import_task_id=$(aws ec2 import-snapshot --description '${{ inputs.firmware_image_name }}' --disk-container 'Format=raw,UserBucket={S3Bucket=${{ inputs.firmware_image_s3_bucket }},S3Key=${{ inputs.firmware_image_name }}}' | jq -r '.ImportTaskId')" >> $GITHUB_OUTPUT

    - name: Wait for import task to complete and get snapshot ID
      id: get_snapshot_id
      shell: bash
      run: |
        IMPORT_TASK_STATUS=""
        while [[ $IMPORT_TASK_STATUS != 'completed' ]]; do
          IMPORT_TASK_STATUS=$(aws ec2 describe-import-snapshot-tasks --import-task-ids ${{ steps.import_snapshot.outputs.import_task_id }} | jq -r '.ImportSnapshotTasks[].SnapshotTaskDetail.Status')
          echo "Import task status is $IMPORT_TASK_STATUS, waiting for completion."
        done
        echo "id=$(aws ec2 describe-import-snapshot-tasks --import-task-ids ${{ steps.import_snapshot.outputs.import_task_id }} | jq -r '.ImportSnapshotTasks[].SnapshotTaskDetail.SnapshotId')" >> $GITHUB_OUTPUT

    - name: Tag snapshot with image name
      shell: bash
      run: |
        aws ec2 create-tags --resources ${{ steps.get_snapshot_id.outputs.id }} --tags 'Key=Name,Value=${{ inputs.firmware_image_name }}'

    - name: Register AMI based on snapshot
      shell: bash
      run: |
        aws ec2 register-image --name '${{ inputs.firmware_image_name }}' --root-device-name /dev/xvda --block-device-mappings 'DeviceName=/dev/xvda,Ebs={SnapshotId=${{ steps.get_snapshot_id.outputs.id }}}'
