name: push-test-components

permissions:
  contents: write

on:
  workflow_dispatch:
    inputs:
      tag:
        description: "The tag to be used when pushing components to the Docker Hub."
        required: true
        type: string
      ref:
        description: "The ref (branch or SHA) to process"
        required: false
        type: string

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

jobs:
  push-components:
    runs-on: ubuntu-24.04
    steps:
      - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8
        with:
          ref: ${{ github.event.inputs.ref }} # Use the ref if provided, otherwise defaults to the current branch/commit

      - uses: nixbuild/nix-quick-install-action@2c9db80fb984ceb1bcaa77cdda3fdf8cfba92035
        with:
          github_access_token: ${{ secrets.GITHUB_TOKEN }}

      - name: Populate the nix store
        run: nix develop --command echo

      - name: Log in to Docker Hub
        run: |
          echo "$DOCKER_HUB_TOKEN" | docker login -u "$DOCKER_HUB_USERNAME" --password-stdin
        env:
          DOCKER_HUB_USERNAME: ${{ secrets.DOCKER_HUB_USERNAME }}
          DOCKER_HUB_TOKEN: ${{ secrets.DOCKER_HUB_TOKEN }}

      - name: Push test components
        run: |
          nix develop --command ./scripts/push-test-components.sh $TAG
        env:
          TAG: ${{ github.event.inputs.tag }}

      - name: Configure git before push
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"

      - name: Generate Unique Branch Name
        id: branch-name
        run: echo "branch_name=bump-test-components-$(date +'%Y%m%d-%H%M%S')" >> $GITHUB_OUTPUT

      - name: Push obelisk-oci.toml
        run: |
          git checkout -b ${{ steps.branch-name.outputs.branch_name }}
          git add obelisk.toml
          git commit -m "chore: Bump test components to $TAG"
          git push origin ${{ steps.branch-name.outputs.branch_name }}
          OWNER=$(echo "${{ github.repository }}" | cut -d'/' -f1)
          REPO=$(echo "${{ github.repository }}" | cut -d'/' -f2)
          curl -v --fail -X POST \
            -H "Content-Type: application/json" \
            -H "Authorization: Bearer $GITHUB_TOKEN" \
            https://api.github.com/repos/$OWNER/$REPO/pulls \
            -d '{
              "title": "chore: Bump test components",
              "head": "'${{ steps.branch-name.outputs.branch_name }}'",
              "base": "main",
              "body": ""
            }'

        env:
          TAG: ${{ github.event.inputs.tag }}
          GITHUB_TOKEN: ${{ secrets.GH_TOKEN_PR_RW }}
