name: Build and push docker image
author: Jeff Kim & Bolt lee
description: 'Build and push docker image'
inputs:
  repository:
    description: '' # Filled out description.
    required: true
    default: 'sample-repository'
  registry:
    description: '' # Filled out description.
    required: true
    default: 'sample-registry'
  dockerfile:
    description: '' # Filled out description.
    required: true
    default: Dockerfile
  file-changes:
    description: 'file pattern list for checking rebuilding image or not'
    required: false
    default: ''
  file-ignore-changes:
    description: 'file pattern list for checking rebuilding image or not'
    required: false
    default: ''
  extra-build-args:
    description: ''
    required: false
    default: ''
  base_sha:
    description: ''
    required: false
    default: ''
  sha:
    description: ''
    required: false
    default: ''
    
runs:
  using: "composite"
  steps:
  - name: Get specific changed files
    id: changed-files
    uses: tj-actions/changed-files@v31
    with:
      sha: ${{ inputs.sha }}
      base_sha: ${{ inputs.base_sha }}
      files: |
        ${{ inputs.file-ignore-changes }}
  - name: Login to Amazon ECR
    id: login-ecr
    uses: aws-actions/amazon-ecr-login@v2
  - name: no source files changes - add current tag to latest image
    if: ( steps.changed-files.outputs.any_changed == 'false' ) || ( github.ref_type == 'tag' )
    shell: bash
    run: |
       echo "REF TYPE:${{ github.ref_type }}"
       echo "Result: pull & push"
       echo "any_changed:${{ steps.changed-files.outputs.any_changed }}"
       echo "all_changed_and_modified_files:${{ steps.changed-files.outputs.all_changed_and_modified_files }}"
       
       docker pull ${{ inputs.registry }}/${{ inputs.repository }}:latest
       docker tag ${{ inputs.registry }}/${{ inputs.repository }}:latest ${{ inputs.registry }}/${{ inputs.repository }}:${{ github.sha }}
       docker push ${{ inputs.registry }}/${{ inputs.repository }}:${{ github.sha }}
  - name: source files changes - build new image
    if: ${{ steps.changed-files.outputs.any_changed == 'true' }}
    shell: bash
    run: |
      echo "Result: build & push"
      echo "any_changed:${{ steps.changed-files.outputs.any_changed }}"
      echo "all_changed_and_modified_files:${{ steps.changed-files.outputs.all_changed_and_modified_files }}"
       
      docker build -f ${GITHUB_WORKSPACE}/${{ inputs.dockerfile }} . \
      --tag ${{ inputs.registry }}/${{ inputs.repository }}:latest \
      --tag ${{ inputs.registry }}/${{ inputs.repository }}:${{ github.sha }}
      docker push ${{ inputs.registry }}/${{ inputs.repository }}:latest
      docker push ${{ inputs.registry }}/${{ inputs.repository }}:${{ github.sha }}
