name: "Build and push image"
description: "Builds and pushes an image to a registry"

inputs:
  service:
    description: "Service to build"
    required: true
  registry_host:
    description: "Image registry host e.g. myacr.azureacr.io"
    required: true
  registry_endpoint:
    description: "Image registry repo e.g. myacr.azureacr.io/eshop"
    required: true
  image_name:
    description: "Name of image"
    required: true
  registry_username:
    description: "Registry username"
    required: true
  registry_password:
    description: "Registry password"
    required: true
  
runs:
  using: "composite"
  steps:
  - name: Enable experimental features for the Docker daemon and CLI
    shell: bash
    run: |
        echo $'{\n  "experimental": true\n}' | sudo tee /etc/docker/daemon.json
        mkdir -p ~/.docker
        echo $'{\n  "experimental": "enabled"\n}' | sudo tee ~/.docker/config.json
        sudo service docker restart
        docker version -f '{{.Client.Experimental}}'
        docker version -f '{{.Server.Experimental}}'

  - name: Login to Container Registry
    uses: docker/login-action@v1
    with:
      registry: ${{ inputs.registry_host }}
      username: ${{ inputs.registry_username }}
      password: ${{ inputs.registry_password }}

  - name: Set branch name as env variable
    run: |
      currentbranch=$(echo ${GITHUB_REF##*/})
      echo "running on $currentbranch"
      echo "BRANCH=$currentbranch" >> $GITHUB_ENV
    shell: bash

  - name: Compose build ${{ inputs.service }}
    shell: bash
    run: sudo -E docker-compose build ${{ inputs.service }}
    working-directory: ./src
    env:
      TAG: ${{ env.BRANCH }}
      REGISTRY: ${{ inputs.registry_endpoint }}

  - name: Compose push ${{ inputs.service }}
    shell: bash
    run: sudo -E docker-compose push ${{ inputs.service }}
    working-directory: ./src
    env:
      TAG: ${{ env.BRANCH }}
      REGISTRY: ${{ inputs.registry_endpoint }}

  - name: Create multiarch manifest
    shell: bash
    run: |
      docker --config ~/.docker manifest create ${{ inputs.registry_endpoint  }}/${{ inputs.image_name }}:${{ env.BRANCH  }} ${{ inputs.registry_endpoint  }}/${{ inputs.image_name  }}:linux-${{ env.BRANCH  }}
      docker --config ~/.docker manifest push ${{ inputs.registry_endpoint  }}/${{ inputs.image_name }}:${{ env.BRANCH  }}