# TODO: Use flakes to generate the docker image

name: release-4-push-docker-image

on:
  workflow_dispatch:
    inputs:
      ref:
        description: "The ref (branch or SHA) to process"
        required: false
        type: string
      skip_latest:
        description: "skip_latest: Tag latest will be pushed unless skip_latest=true"
        required: true
        type: boolean
        default: false
  workflow_call:
    inputs:
      skip_latest:
        description: "skip_latest: Tag latest will be pushed unless skip_latest=true"
        required: true
        type: boolean
        default: false

defaults:
  run:
    shell: bash -xe {0}

jobs:
  push-image:
    name: ${{ matrix.dockerfile }}
    runs-on: ubuntu-24.04
    strategy:
      fail-fast: false
      matrix:
        include:
          - tarfile: obelisk-x86_64-unknown-linux-gnu.tar.gz
            dockerfile: ubuntu-24.04.Dockerfile
            image_tag: ubuntu

          - tarfile: obelisk-x86_64-unknown-linux-gnu.tar.gz
            dockerfile: ubuntu-24.04-litestream.Dockerfile
            image_tag: ubuntu-litestream

          - tarfile: obelisk-x86_64-unknown-linux-musl.tar.gz
            dockerfile: alpine.Dockerfile
            image_tag: alpine

    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8
        with:
          # Use the ref if provided, otherwise obtain the parent workflow branch, defaults to main.
          ref: ${{ github.event.inputs.ref || github.event.workflow_run.head_branch }}

      - id: git-info
        run: |
          VERSION="$(grep -m1 '^version = "' Cargo.toml | cut -d'"' -f2)"
          echo "version=$VERSION" >> $GITHUB_OUTPUT
          echo "tag=v$VERSION" >> $GITHUB_OUTPUT
          echo "sha=$(git rev-parse HEAD)" >> $GITHUB_OUTPUT

      - run: |
          docker login -u getobelisk -p ${{ secrets.DOCKER_HUB_TOKEN }}
          mkdir tmp
          cd tmp
          wget -q https://github.com/obeli-sk/obelisk/releases/download/${TAG}/${{ matrix.tarfile }}
          tar xvfz ${{ matrix.tarfile }}
          cp ../obelisk.toml obelisk.toml
          IMAGE_BASE="getobelisk/obelisk"
          IMAGE="${IMAGE_BASE}:${{ matrix.image_tag }}"
          docker build --progress=plain -f ../.github/workflows/release/docker-image/${{ matrix.dockerfile }} . --tag $IMAGE
          docker push $IMAGE


          echo "Tagging with version ${VERSION}"
          IMAGE2="${IMAGE_BASE}:${VERSION}-${{ matrix.image_tag }}"
          echo "Tagging as $IMAGE2"
          docker tag $IMAGE $IMAGE2
          docker push $IMAGE2

          if [ "${{ inputs.skip_latest }}" = "true" ]; then
            echo "Skipping latest tag"
          elif [ "${{ matrix.image_tag }}" = "ubuntu" ]; then
            docker tag $IMAGE $IMAGE_BASE:latest
            docker push $IMAGE_BASE:latest
          fi
        env:
          TAG: ${{ steps.git-info.outputs.tag }}
          VERSION: ${{ steps.git-info.outputs.version }}
