name: Nightly Runtime Artifacts

on:
  push:
    branches:
      - main
    paths:
      - "src/**"
      - "pom.xml"
      - "mvnw"
      - "mvnw.cmd"
      - ".github/workflows/nightly-artifacts.yml"
  workflow_dispatch:

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

permissions:
  contents: write
  packages: write

jobs:
  build-windows-zip:
    name: Build Windows ZIP
    runs-on: windows-latest

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

      - name: Resolve nightly version info
        shell: pwsh
        run: |
          $xml = [xml](Get-Content pom.xml)
          $version = $xml.project.version
          $shortSha = "${{ github.sha }}".Substring(0, 7)
          Add-Content -Path $env:GITHUB_ENV -Value "VERSION=$version"
          Add-Content -Path $env:GITHUB_ENV -Value "SHORT_SHA=$shortSha"
          Add-Content -Path $env:GITHUB_ENV -Value "ASSET_BASENAME=praktiKST-$version-$shortSha"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Install WiX Toolset
        shell: pwsh
        run: choco install wixtoolset --no-progress -y

      - name: Build JAR and copy runtime dependencies
        shell: pwsh
        run: |
          .\mvnw.cmd -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          $jar = Get-ChildItem -Path target -Filter 'praktiKST-*.jar' | Sort-Object LastWriteTime -Descending | Select-Object -First 1
          if (-not $jar) {
            throw "No project JAR produced"
          }
          Copy-Item $jar.FullName target/dist-libs/app.jar

      - name: Build app-image with jpackage
        shell: pwsh
        run: |
          New-Item -ItemType Directory -Force -Path dist | Out-Null
          jpackage --type app-image --name praktiKST --input target/dist-libs --main-jar app.jar --main-class kst4contest.view.Kst4ContestApplication --module-path target/dist-libs --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec --dest dist

      - name: Create Windows ZIP
        shell: pwsh
        run: |
          if (-not (Test-Path dist/praktiKST)) {
            throw "No Windows app-image produced by jpackage"
          }
          Compress-Archive -Path dist/praktiKST -DestinationPath "dist/$env:ASSET_BASENAME-windows-x64.zip" -Force

      - name: Upload Windows artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: windows-zip
          path: dist/praktiKST-*-windows-x64.zip
          retention-days: 14

  build-linux-appimage:
    name: Build Linux AppImage
    runs-on: ubuntu-latest

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Build JAR and copy runtime dependencies
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar

      - name: Build app-image with jpackage
        run: |
          mkdir -p dist
          jpackage \
            --type app-image \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --dest dist

      - name: Create AppDir metadata
        run: |
          rm -rf target/KST4Contest.AppDir
          cp -a dist/KST4Contest target/KST4Contest.AppDir

          cat > target/KST4Contest.AppDir/AppRun << 'EOF'
          #!/bin/sh
          HERE="$(dirname "$(readlink -f "$0")")"
          exec "$HERE/bin/KST4Contest" "$@"
          EOF
          chmod +x target/KST4Contest.AppDir/AppRun

          cat > target/KST4Contest.AppDir/KST4Contest.desktop << 'EOF'
          [Desktop Entry]
          Type=Application
          Name=KST4Contest
          Exec=KST4Contest
          Icon=KST4Contest
          Categories=Network;HamRadio;
          Terminal=false
          EOF

          if [ -f target/KST4Contest.AppDir/lib/KST4Contest.png ]; then
            cp target/KST4Contest.AppDir/lib/KST4Contest.png target/KST4Contest.AppDir/KST4Contest.png
          fi

      - name: Build AppImage
        run: |
          wget -q -O target/appimagetool.AppImage https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage
          chmod +x target/appimagetool.AppImage
          APPIMAGE_EXTRACT_AND_RUN=1 ARCH=x86_64 target/appimagetool.AppImage target/KST4Contest.AppDir "dist/${ASSET_BASENAME}-linux-x86_64.AppImage"

      - name: Upload Linux artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: linux-appimage
          path: dist/KST4Contest-*-linux-x86_64.AppImage
          retention-days: 14

  build-linux-deb:
    name: Build Debian package
    runs-on: ubuntu-latest

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Install packaging dependencies
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends fakeroot

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Build JAR and copy runtime dependencies
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar

      - name: Build Debian package
        run: |
          mkdir -p dist
          jpackage \
            --type deb \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --linux-package-deps "libgstreamer1.0-0,libgstreamer-plugins-base1.0-0,gstreamer1.0-plugins-good" \
            --dest dist
          DEB="$(ls dist/*.deb | head -n 1)"
          if [ -z "$DEB" ]; then
            echo "No DEB produced by jpackage" && exit 1
          fi
          mv "$DEB" "dist/${ASSET_BASENAME}-debian-amd64.deb"

      - name: Upload Debian artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: linux-debian
          path: dist/KST4Contest-*-debian-amd64.deb
          retention-days: 14

  build-linux-rpm:
    name: Build Fedora package
    runs-on: ubuntu-latest

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Install packaging dependencies
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends rpm

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Build JAR and copy runtime dependencies
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar

      - name: Build Fedora package
        run: |
          mkdir -p dist
          jpackage \
            --type rpm \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --linux-package-deps "gstreamer1,gstreamer1-plugins-base,gstreamer1-plugins-good" \
            --dest dist
          RPM="$(ls dist/*.rpm | head -n 1)"
          if [ -z "$RPM" ]; then
            echo "No RPM produced by jpackage" && exit 1
          fi
          mv "$RPM" "dist/${ASSET_BASENAME}-fedora-x86_64.rpm"

      - name: Upload Fedora artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: linux-fedora
          path: dist/KST4Contest-*-fedora-x86_64.rpm
          retention-days: 14

  build-linux-arch:
    name: Build Arch Linux package
    runs-on: ubuntu-latest

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          echo "VERSION=$VERSION" >> "$GITHUB_ENV"
          echo "SHORT_SHA=$SHORT_SHA" >> "$GITHUB_ENV"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Install packaging dependencies
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends zstd

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Build JAR and copy runtime dependencies
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar

      - name: Build app-image with jpackage
        run: |
          mkdir -p dist
          jpackage \
            --type app-image \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --dest dist

      - name: Build Arch Linux package artifact
        run: |
          ARCH=$(uname -m)
          PKGVER=$(printf '%s' "${VERSION}-${SHORT_SHA}" | sed 's/[^[:alnum:].+_]/_/g')
          PKGROOT="target/archpkg"
          rm -rf "$PKGROOT"
          mkdir -p "$PKGROOT/usr/lib/KST4Contest" "$PKGROOT/usr/bin"
          cp -a dist/KST4Contest/. "$PKGROOT/usr/lib/KST4Contest/"
          cat > "$PKGROOT/usr/bin/KST4Contest" << 'EOF'
          #!/bin/sh
          exec /usr/lib/KST4Contest/bin/KST4Contest "$@"
          EOF
          chmod 755 "$PKGROOT/usr/bin/KST4Contest"
          mkdir -p "$PKGROOT/usr/share/applications" "$PKGROOT/usr/share/icons/hicolor/256x256/apps"
          cat > "$PKGROOT/usr/share/applications/KST4Contest.desktop" << 'EOF'
          [Desktop Entry]
          Type=Application
          Name=KST4Contest
          Comment=ON4KST Chat Client for VHF/UHF contest operation
          Exec=KST4Contest
          Icon=KST4Contest
          Categories=Network;HamRadio;
          Terminal=false
          EOF
          if [ -f "$PKGROOT/usr/lib/KST4Contest/lib/KST4Contest.png" ]; then
            cp "$PKGROOT/usr/lib/KST4Contest/lib/KST4Contest.png" "$PKGROOT/usr/share/icons/hicolor/256x256/apps/KST4Contest.png"
          fi
          INSTALLED_SIZE=$(du -sb "$PKGROOT" | cut -f1)
          BUILDDATE=$(date +%s)
          WORKFLOW_SHA256=$(sha256sum "$GITHUB_WORKSPACE/.github/workflows/nightly-artifacts.yml" | awk '{print $1}')
          {
            echo "pkgname = kst4contest"
            echo "pkgbase = kst4contest"
            echo "xdata = pkgtype=pkg"
            echo "pkgver = ${PKGVER}-1"
            echo "pkgdesc = KST4Contest amateur radio contest logger"
            echo "url = https://github.com/${{ github.repository }}"
            echo "builddate = ${BUILDDATE}"
            echo "packager = GitHub Actions"
            echo "size = ${INSTALLED_SIZE}"
            echo "arch = ${ARCH}"
            echo "license = custom"
            echo "depend = java-runtime"
            echo "depend = gst-plugins-base"
            echo "depend = gst-plugins-good"
          } > "$PKGROOT/.PKGINFO"
          {
            echo "format = 2"
            echo "pkgname = kst4contest"
            echo "pkgbase = kst4contest"
            echo "pkgver = ${PKGVER}-1"
            echo "pkgarch = ${ARCH}"
            echo "pkgbuild_sha256sum = ${WORKFLOW_SHA256}"
            echo "packager = GitHub Actions"
            echo "builddate = ${BUILDDATE}"
            echo "builddir = /build"
            echo "startdir = /build"
            echo "buildtool = makepkg"
            echo "buildtoolver = 7.0.0-1-x86_64"
            echo "buildenv = !distcc !color !ccache check !sign"
            echo "options = !strip docs libtool staticlibs emptydirs zipman purge !debug !lto"
          } > "$PKGROOT/.BUILDINFO"
          tar --zstd --transform 's|^\./||' -cf "dist/${ASSET_BASENAME}-archlinux-${ARCH}.pkg.tar.zst" -C "$PKGROOT" .

      - name: Upload Arch Linux artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: linux-arch
          path: dist/KST4Contest-*-archlinux-*.pkg.tar.zst
          retention-days: 14

  build-flatpak:
    name: Build Flatpak
    runs-on: ubuntu-latest

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          echo "VERSION=$VERSION" >> "$GITHUB_ENV"
          echo "SHORT_SHA=$SHORT_SHA" >> "$GITHUB_ENV"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Install Flatpak tooling
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends flatpak flatpak-builder elfutils
          flatpak remote-add --user --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
          flatpak --user install -y flathub org.freedesktop.Platform//24.08 org.freedesktop.Sdk//24.08

      - name: Build app-image with jpackage
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar
          mkdir -p target/flatpak-src
          jpackage \
            --type app-image \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --dest target/flatpak-src

      - name: Create Flatpak manifest
        run: |
          mkdir -p dist
          cat > target/de.x08.KST4Contest.yml << 'EOF'
          app-id: de.x08.KST4Contest
          runtime: org.freedesktop.Platform
          runtime-version: "24.08"
          sdk: org.freedesktop.Sdk
          command: KST4Contest
          finish-args:
            - --socket=wayland
            - --socket=x11
            - --socket=pulseaudio
            - --share=network
            - --share=ipc
            - --device=dri
            - --filesystem=~/.praktiKST
            - --env=ALSA_CONFIG_PATH=/app/share/alsa/asound.conf
          modules:
            - name: kst4contest
              buildsystem: simple
              build-commands:
                - install -d /app/lib/KST4Contest /app/bin /app/share/applications /app/share/alsa
                - printf '@include /usr/share/alsa/alsa.conf\npcm.!default { type pulse }\nctl.!default { type pulse }\n' > /app/share/alsa/asound.conf
                - cp -a . /app/lib/KST4Contest/
                - printf '#!/bin/sh\nexec /app/lib/KST4Contest/bin/KST4Contest "$@"\n' > /app/bin/KST4Contest
                - chmod 755 /app/bin/KST4Contest
                - echo '[Desktop Entry]' > /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Type=Application' >> /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Name=KST4Contest' >> /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Comment=ON4KST Chat Client for VHF/UHF contest operation' >> /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Exec=KST4Contest' >> /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Icon=de.x08.KST4Contest' >> /app/share/applications/de.x08.KST4Contest.desktop
                - printf 'Categories=Network;HamRadio;\n' >> /app/share/applications/de.x08.KST4Contest.desktop
                - echo 'Terminal=false' >> /app/share/applications/de.x08.KST4Contest.desktop
                - test -f /app/lib/KST4Contest/lib/KST4Contest.png && install -Dm644 /app/lib/KST4Contest/lib/KST4Contest.png /app/share/icons/hicolor/256x256/apps/de.x08.KST4Contest.png || true
              sources:
                - type: dir
                  path: flatpak-src/KST4Contest
          EOF

      - name: Import Flatpak signing key
        run: |
          echo "${{ secrets.FLATPAK_GPG_PRIVATE_KEY }}" | gpg --batch --import
          FLATPAK_GPG_KEY_ID=$(gpg --list-secret-keys --with-colons | awk -F: '/^fpr/{print $10; exit}')
          echo "FLATPAK_GPG_KEY_ID=$FLATPAK_GPG_KEY_ID" >> "$GITHUB_ENV"

      - name: Build Flatpak repo (nightly)
        run: |
          flatpak-builder --force-clean target/flatpak-build target/de.x08.KST4Contest.yml
          flatpak build-export --gpg-sign="$FLATPAK_GPG_KEY_ID" target/flatpak-repo target/flatpak-build nightly
          flatpak build-update-repo --gpg-sign="$FLATPAK_GPG_KEY_ID" target/flatpak-repo

      - name: Create flatpakref (nightly)
        run: |
          REPO_NAME="${GITHUB_REPOSITORY#*/}"
          PAGES_URL="https://${GITHUB_REPOSITORY_OWNER}.github.io/${REPO_NAME}/"
          GPG_KEY_B64=$(gpg --export "$FLATPAK_GPG_KEY_ID" | base64 -w 0)
          cat > "dist/de.x08.KST4Contest.nightly.flatpakref" << EOF
          [Flatpak Ref]
          Name=de.x08.KST4Contest
          Branch=nightly
          Title=KST4Contest (Nightly) – ON4KST Chat Client
          Url=${PAGES_URL}
          RuntimeRepo=https://flathub.org/repo/flathub.flatpakrepo
          GPGKey=${GPG_KEY_B64}
          IsRuntime=false
          EOF

      - name: Upload flatpakref
        uses: actions/upload-artifact@v4.3.4
        with:
          name: flatpakref
          path: dist/de.x08.KST4Contest.nightly.flatpakref

      - name: Upload Flatpak OSTree repo
        uses: actions/upload-artifact@v4.3.4
        with:
          name: flatpak-ostree-repo
          path: target/flatpak-repo/

  publish-flatpak-repo:
    name: Publish Flatpak OSTree Repo (nightly)
    runs-on: ubuntu-latest
    needs: build-flatpak

    steps:
      - name: Install Flatpak tooling
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends flatpak

      - name: Import Flatpak signing key
        run: |
          echo "${{ secrets.FLATPAK_GPG_PRIVATE_KEY }}" | gpg --batch --import
          echo "FLATPAK_GPG_KEY_ID=$(gpg --list-secret-keys --with-colons | awk -F: '/^fpr/{print $10; exit}')" >> "$GITHUB_ENV"

      - name: Download OSTree repo artifact
        uses: actions/download-artifact@v4.1.3
        with:
          name: flatpak-ostree-repo
          path: flatpak-ostree-repo/

      - name: Checkout existing flatpak-repo branch
        uses: actions/checkout@v4.1.7
        with:
          ref: flatpak-repo
          path: existing-flatpak-repo

      - name: Merge nightly build into flatpak-repo
        run: |
          cd existing-flatpak-repo
          git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config user.name "github-actions[bot]"
          # Copy the new OSTree build into the repo
          rsync -a ../flatpak-ostree-repo/ ./
          # Regenerate summary with all branches
          flatpak build-update-repo --gpg-sign="$FLATPAK_GPG_KEY_ID" .
          # Generate .flatpakrepo with embedded GPG key so users can do remote-add without errors
          REPO_NAME="${GITHUB_REPOSITORY#*/}"
          PAGES_URL="https://${GITHUB_REPOSITORY_OWNER}.github.io/${REPO_NAME}/"
          GPG_KEY_B64=$(gpg --export "$FLATPAK_GPG_KEY_ID" | base64 -w 0)
          cat > kst4contest.flatpakrepo << EOF
          [Flatpak Repo]
          Title=KST4Contest
          Url=${PAGES_URL}
          Homepage=https://github.com/${GITHUB_REPOSITORY}
          Comment=KST4Contest – ON4KST Chat Client for VHF/UHF contests
          GPGKey=${GPG_KEY_B64}
          EOF
          # Stage all changes (new/updated refs, summary, objects in OSTree)
          git add -A
          if git diff --cached --quiet; then
            echo "No changes to commit"
          else
            git commit -m "Nightly flatpak: $(echo ${{ github.sha }} | cut -c1-7)"
            git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git HEAD:flatpak-repo
          fi

  build-macos-dmg:
    name: Build macOS DMG (${{ matrix.os }})
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        os: [macos-latest, macos-15-intel]

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

      - name: Resolve nightly version info
        run: |
          VERSION=$(grep -m1 '<version>' pom.xml | sed 's/.*<version>\(.*\)<\/version>.*/\1/')
          SHORT_SHA="${GITHUB_SHA::7}"
          ARCH=$(uname -m)
          echo "VERSION=$VERSION" >> "$GITHUB_ENV"
          echo "SHORT_SHA=$SHORT_SHA" >> "$GITHUB_ENV"
          echo "ASSET_BASENAME=KST4Contest-${VERSION}-${SHORT_SHA}" >> "$GITHUB_ENV"
          echo "ARCH=$ARCH" >> "$GITHUB_ENV"

      - name: Set up Java 21
        uses: actions/setup-java@v4.1.0
        with:
          distribution: temurin
          java-version: "21"

      - name: Ensure mvnw is executable
        run: chmod +x mvnw

      - name: Build JAR and copy runtime dependencies
        run: |
          ./mvnw -B -DskipTests package dependency:copy-dependencies -DincludeScope=runtime -DoutputDirectory=target/dist-libs
          cp "$(ls -t target/praktiKST-*.jar | head -n 1)" target/dist-libs/app.jar

      - name: Build macOS DMG with jpackage
        run: |
          mkdir -p dist
          jpackage \
            --type dmg \
            --name KST4Contest \
            --input target/dist-libs \
            --main-jar app.jar \
            --main-class kst4contest.view.Kst4ContestApplication \
            --module-path target/dist-libs \
            --add-modules javafx.controls,javafx.graphics,javafx.fxml,javafx.web,javafx.media,java.sql,java.net.http,jdk.crypto.ec \
            --dest dist

        env:
          MACOSX_DEPLOYMENT_TARGET: "13.0"

      - name: Rename DMG artifact
        run: |
          DMG=$(ls dist/*.dmg | head -n 1)
          if [ -z "$DMG" ]; then
            echo "No DMG produced by jpackage" && exit 1
          fi
          mv "$DMG" "dist/${ASSET_BASENAME}-macos-${ARCH}.dmg"

      - name: Upload macOS artifact
        uses: actions/upload-artifact@v4.3.4
        with:
          name: macos-dmg-${{ matrix.os }}
          path: dist/KST4Contest-*-macos-*.dmg
          retention-days: 14
