###############################################################################
# Forgejo Actions - build, sign, and push the KAMOS Gaming OS image
#
# Configured for: cgi.medsys.cloud/mkm1971/kamos
# Runner labels:  ubuntu-latest / ubuntu-24.04 / ubuntu-22.04 (Forgejo runner v0.4.1)
#
# Prereqs in your Forgejo repo:
#   1. Container Registry feature enabled on cgi.medsys.cloud.
#   2. The runner host must be x86_64 (Bazzite NVIDIA is x86_64 only).
#   3. Repository secrets at /mkm1971/kamos/settings/actions/secrets:
#        - SIGNING_SECRET     contents of cosign.key (NOT the .pub)
#        - REGISTRY_USER      mkm1971
#        - REGISTRY_TOKEN     Forgejo access token with `package` write scope
###############################################################################

name: build-image

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]
  schedule:
    # Rebuild weekly so we pick up base-image security updates.
    - cron: "0 6 * * 1"
  workflow_dispatch:

env:
  IMAGE_NAME: kamos
  IMAGE_TAGS: "stable latest"
  # Override this in your Forgejo repo's variables to point at your instance.
  REGISTRY: ${{ vars.REGISTRY || 'cgi.medsys.cloud' }}
  REGISTRY_USER: ${{ secrets.REGISTRY_USER }}
  REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}

jobs:
  build:
    name: Build & push (${{ matrix.platform }})
    # Matches your runner labels: ubuntu-latest / ubuntu-24.04 / ubuntu-22.04
    # Assumes the runner host is x86_64 - if it's actually Apple Silicon, the
    # build will hit "exec format error" and we'll need to add binfmt qemu setup.
    runs-on: ubuntu-latest
    permissions:
      contents: read
      packages: write
    strategy:
      fail-fast: false
      matrix:
        platform: [linux/amd64]

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Compute tags
        id: tags
        shell: bash
        run: |
          DATE_TAG="$(date +%Y%m%d)"
          SHA_TAG="${GITHUB_SHA::7}"
          {
            echo "date_tag=${DATE_TAG}"
            echo "sha_tag=${SHA_TAG}"
            echo "image_ref=${REGISTRY}/${{ gitea.repository_owner }}/${IMAGE_NAME}"
          } >> "$GITHUB_OUTPUT"

      - name: Install build tooling
        shell: bash
        run: |
          sudo apt-get update -y
          sudo apt-get install -y podman buildah skopeo cosign jq

      - name: Build image
        id: build
        shell: bash
        env:
          IMAGE_REF: ${{ steps.tags.outputs.image_ref }}
          DATE_TAG: ${{ steps.tags.outputs.date_tag }}
          SHA_TAG:  ${{ steps.tags.outputs.sha_tag }}
        run: |
          set -euxo pipefail
          podman build \
            --platform=${{ matrix.platform }} \
            --pull=newer \
            --tag "${IMAGE_REF}:${DATE_TAG}" \
            --tag "${IMAGE_REF}:${SHA_TAG}" \
            $(for t in $IMAGE_TAGS; do echo --tag "${IMAGE_REF}:${t}"; done) \
            .

      - name: Login to Forgejo container registry
        if: github.event_name != 'pull_request'
        shell: bash
        run: |
          echo "${REGISTRY_TOKEN}" | podman login \
            --username "${REGISTRY_USER}" \
            --password-stdin \
            "${REGISTRY}"

      - name: Push image
        if: github.event_name != 'pull_request'
        shell: bash
        env:
          IMAGE_REF: ${{ steps.tags.outputs.image_ref }}
          DATE_TAG:  ${{ steps.tags.outputs.date_tag }}
          SHA_TAG:   ${{ steps.tags.outputs.sha_tag }}
        run: |
          set -euxo pipefail
          for tag in $DATE_TAG $SHA_TAG $IMAGE_TAGS; do
            podman push "${IMAGE_REF}:${tag}"
          done

      - name: Sign image with cosign
        if: github.event_name != 'pull_request'
        shell: bash
        env:
          COSIGN_PRIVATE_KEY: ${{ secrets.SIGNING_SECRET }}
          COSIGN_PASSWORD: ""
          IMAGE_REF: ${{ steps.tags.outputs.image_ref }}
        run: |
          set -euxo pipefail
          for tag in $IMAGE_TAGS; do
            DIGEST=$(skopeo inspect --format '{{.Digest}}' "docker://${IMAGE_REF}:${tag}")
            cosign sign --yes --key env://COSIGN_PRIVATE_KEY "${IMAGE_REF}@${DIGEST}"
          done

      - name: Summary
        shell: bash
        env:
          IMAGE_REF: ${{ steps.tags.outputs.image_ref }}
        run: |
          {
            echo "### Built image"
            echo ""
            echo "\`${IMAGE_REF}\` with tags: ${IMAGE_TAGS}"
            echo ""
            echo "Switch a target machine to this image with:"
            echo ""
            echo "\`\`\`"
            echo "sudo bootc switch ${IMAGE_REF}:stable"
            echo "\`\`\`"
          } >> "$GITHUB_STEP_SUMMARY"
