name: "Docker Push"
description: "Push to docker registry"

inputs:
  server_url:
    required: true
  repository:
    required: true
  tag:
    required: true

runs:
  using: "composite"
  steps:
    - name: Set env
      shell: bash
      run: |
        REGISTRY=$(basename ${{ inputs.server_url }})

        NR=${{ inputs.repository }}
        NAMESPACE="${NR%%/*}"
        REPOSITORY="${NR##*/}"

        TAG=${{ inputs.tag }}
        VERSION=${TAG#v}

        echo "REGISTRY=${REGISTRY}" >> $GITHUB_ENV
        echo "NAMESPACE=${NAMESPACE}" >> $GITHUB_ENV
        echo "REPOSITORY=${REPOSITORY}" >> $GITHUB_ENV
        echo "VERSION=${VERSION}" >> $GITHUB_ENV

    - name: Push images
      shell: bash
      run: |
        docker image tag $REPOSITORY:$VERSION-amd64 $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64
        docker push $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64

        docker image tag $REPOSITORY:$VERSION-arm64 $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64
        docker push $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64

        docker image tag $REPOSITORY:$VERSION-arm $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm
        docker push $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm

    - name: Push manifest
      shell: bash
      run: |
        docker manifest create $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64 \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64 \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64 --arch amd64
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64 --arch arm64
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm --arch arm
        docker manifest push $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION

        docker manifest create $REGISTRY/$NAMESPACE/$REPOSITORY:latest \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64 \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64 \
          $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:latest $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-amd64 --arch amd64
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:latest $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm64 --arch arm64
        docker manifest annotate $REGISTRY/$NAMESPACE/$REPOSITORY:latest $REGISTRY/$NAMESPACE/$REPOSITORY:$VERSION-arm --arch arm
        docker manifest push $REGISTRY/$NAMESPACE/$REPOSITORY:latest
