name: Build Image
inputs:
  platform:
    description: "Platform to build for"
    required: true
    example: "linux/amd64"
  target:
    description: "Target to build"
    required: true
    example: "docker"
  baseimg:
    description: "Base image type"
    required: true
    example: "docker"
  suffix:
    description: "Suffix to add to tags"
    required: true
  version:
    description: "Version to build"
    required: true
    example: "2023.12.0"
runs:
  using: "composite"
  steps:
    - name: Generate short tags
      id: tags
      shell: bash
      run: |
        output=$(docker/generate_tags.py \
          --tag "${{ inputs.version }}" \
          --suffix "${{ inputs.suffix }}")
        echo $output
        for l in $output; do
          echo $l >> $GITHUB_OUTPUT
        done

    # set cache-to only if dev branch
    - id: cache-to
      shell: bash
      run: |-
        if [[ "${{ github.ref }}" == "refs/heads/dev" ]]; then
          echo "value=type=gha,mode=max" >> $GITHUB_OUTPUT
        else
          echo "value=" >> $GITHUB_OUTPUT
        fi

    - name: Build and push to ghcr by digest
      id: build-ghcr
      uses: docker/build-push-action@v6.3.0
      with:
        context: .
        file: ./docker/Dockerfile
        platforms: ${{ inputs.platform }}
        target: ${{ inputs.target }}
        cache-from: type=gha
        cache-to: ${{ steps.cache-to.outputs.value }}
        build-args: |
          BASEIMGTYPE=${{ inputs.baseimg }}
          BUILD_VERSION=${{ inputs.version }}
        outputs: |
          type=image,name=ghcr.io/${{ steps.tags.outputs.image_name }},push-by-digest=true,name-canonical=true,push=true

    - name: Export ghcr digests
      shell: bash
      run: |
        mkdir -p /tmp/digests/${{ inputs.target }}/ghcr
        digest="${{ steps.build-ghcr.outputs.digest }}"
        touch "/tmp/digests/${{ inputs.target }}/ghcr/${digest#sha256:}"

    - name: Build and push to dockerhub by digest
      id: build-dockerhub
      uses: docker/build-push-action@v6.3.0
      with:
        context: .
        file: ./docker/Dockerfile
        platforms: ${{ inputs.platform }}
        target: ${{ inputs.target }}
        cache-from: type=gha
        cache-to: ${{ steps.cache-to.outputs.value }}
        build-args: |
          BASEIMGTYPE=${{ inputs.baseimg }}
          BUILD_VERSION=${{ inputs.version }}
        outputs: |
          type=image,name=docker.io/${{ steps.tags.outputs.image_name }},push-by-digest=true,name-canonical=true,push=true

    - name: Export dockerhub digests
      shell: bash
      run: |
        mkdir -p /tmp/digests/${{ inputs.target }}/dockerhub
        digest="${{ steps.build-dockerhub.outputs.digest }}"
        touch "/tmp/digests/${{ inputs.target }}/dockerhub/${digest#sha256:}"