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

    - name: Build and push to ghcr by digest
      id: build-ghcr
      uses: docker/build-push-action@v5.3.0
      with:
        context: .
        file: ./docker/Dockerfile
        platforms: ${{ inputs.platform }}
        target: ${{ inputs.target }}
        cache-from: type=gha
        cache-to: type=gha,mode=max
        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: Upload ghcr digest
      uses: actions/upload-artifact@v3.1.3
      with:
        name: digests-${{ inputs.target }}-ghcr
        path: /tmp/digests/${{ inputs.target }}/ghcr/*
        if-no-files-found: error
        retention-days: 1

    - name: Build and push to dockerhub by digest
      id: build-dockerhub
      uses: docker/build-push-action@v5.3.0
      with:
        context: .
        file: ./docker/Dockerfile
        platforms: ${{ inputs.platform }}
        target: ${{ inputs.target }}
        cache-from: type=gha
        cache-to: type=gha,mode=max
        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:}"

    - name: Upload dockerhub digest
      uses: actions/upload-artifact@v3.1.3
      with:
        name: digests-${{ inputs.target }}-dockerhub
        path: /tmp/digests/${{ inputs.target }}/dockerhub/*
        if-no-files-found: error
        retention-days: 1
