name: Build RPMs

on:
  workflow_dispatch:
    inputs:
      version:
        description: "Version to build (e.g., 1.0.4 or v1.0.4). Leave empty to use main's latest tag."
        required: false
        default: ""
  push:
    tags:
      - "v*"
  pull_request:
    types: [opened, synchronize, reopened, labeled, unlabeled]

permissions:
  contents: write
  pull-requests: write

jobs:
  lint:
    name: Lint Python
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request' || !contains(github.event.pull_request.labels.*.name, 'documentation')

    steps:
      - name: Checkout source
        uses: actions/checkout@v6

      - name: Set up Python
        uses: actions/setup-python@v6
        with:
          python-version: "3.12"

      - name: Install ruff
        run: pip install ruff

      - name: Run ruff
        run: ruff check src/almalinux-creative-installer src/qtcompat.py

  shellcheck:
    name: ShellCheck helper
    runs-on: ubuntu-latest
    if: github.event_name != 'pull_request' || !contains(github.event.pull_request.labels.*.name, 'documentation')

    steps:
      - name: Checkout source
        uses: actions/checkout@v6

      - name: Run ShellCheck
        uses: ludeeus/action-shellcheck@2.0.0
        with:
          additional_files: src/almalinux-creative-installer-helper

  build:
    name: Build (EL${{ matrix.el }})
    runs-on: ubuntu-latest
    needs: [lint, shellcheck]
    if: github.event_name != 'pull_request' || !contains(github.event.pull_request.labels.*.name, 'documentation')
    strategy:
      matrix:
        include:
          - el: 9
            qt_pkg: python3-qt5
          - el: 10
            qt_pkg: python3-pyqt6

    container:
      image: almalinux:${{ matrix.el }}

    steps:
      - name: Install build dependencies
        run: |
          # EL10: enable CRB before EPEL so python3-pyqt6 is resolvable
          if [ "${{ matrix.el }}" -ge "10" ]; then
            dnf config-manager --enable crb
          fi
          dnf -y install epel-release
          dnf -y install \
            rpm-build rpmdevtools git bash \
            python3 \
            ${{ matrix.qt_pkg }} \
            polkit xdg-utils \
            rsync tar findutils

      - name: Checkout source
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Resolve build version
        id: resolve_version
        env:
          INPUT_VERSION: ${{ inputs.version }}
        run: |
          set -euo pipefail
          git config --global --add safe.directory "$GITHUB_WORKSPACE"

          # 1) workflow_dispatch explicit input wins
          if [ -n "${INPUT_VERSION}" ]; then
            VERSION="${INPUT_VERSION#v}"
            echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
            echo "Resolved version from workflow input: ${VERSION}"
            exit 0
          fi

          # 2) Tag pushes use tag name
          if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
            VERSION="${GITHUB_REF#refs/tags/}"
            VERSION="${VERSION#v}"
            echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
            echo "Resolved version from tag: ${VERSION}"
            exit 0
          fi

          # 3) PR builds create beta pre-release from latest stable tag
          if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then
            BASE_TAG="$(git tag --list 'v*' --sort=-v:refname | head -n 1 || true)"
            BASE_VERSION="${BASE_TAG#v}"
            if [ -z "${BASE_VERSION}" ]; then
              BASE_VERSION="0.0.0"
            fi

            SHORT_SHA="$(printf '%s' "$GITHUB_SHA" | cut -c1-8)"
            VERSION="${BASE_VERSION}-beta.pr${{ github.event.pull_request.number }}.${SHORT_SHA}"
            echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
            echo "Resolved version for PR beta build: ${VERSION}"
            exit 0
          fi

          # 4) Fallback for branch manual runs without input
          VERSION="$(git tag --list 'v*' --sort=-v:refname | head -n 1 || true)"
          VERSION="${VERSION#v}"
          if [ -z "${VERSION}" ]; then
            echo "Could not resolve a version (no tags found)."
            exit 1
          fi

          echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
          echo "Resolved version from latest tag fallback: ${VERSION}"

      - name: Build RPM
        env:
          TOPDIR: ${{ github.workspace }}/rpmbuild
          DISTDIR: ${{ github.workspace }}/dist
          VERSION: ${{ steps.resolve_version.outputs.version }}
          GIT_DISCOVERY_ACROSS_FILESYSTEM: 1
        run: |
          mkdir -p "$TOPDIR" "$DISTDIR"
          export HOME="${{ github.workspace }}"
          mkdir -p "$HOME"/rpmbuild
          
          git config --global --add safe.directory "$GITHUB_WORKSPACE"

          chmod +x src/packaging/build-rpm.sh
          ./src/packaging/build-rpm.sh

          find "$HOME/rpmbuild/RPMS" -type f -name "*.rpm" -exec cp -v {} "$DISTDIR/" \;

      - name: Smoke test — install RPM and verify files
        env:
          DISTDIR: ${{ github.workspace }}/dist
        run: |
          dnf install -y "$DISTDIR"/*.rpm
          test -x /usr/bin/almalinux-creative-installer              || { echo "FAIL: binary missing"; exit 1; }
          test -x /usr/libexec/almalinux-creative-installer-helper   || { echo "FAIL: helper missing"; exit 1; }
          test -f /usr/share/almalinux-creative-installer/qtcompat.py || { echo "FAIL: qtcompat missing"; exit 1; }
          test -f /usr/share/applications/almalinux-creative-installer.desktop || { echo "FAIL: .desktop missing"; exit 1; }
          echo "Smoke test passed on EL${{ matrix.el }}."

      - name: Upload RPM artifacts
        uses: actions/upload-artifact@v7
        with:
          name: rpm-el${{ matrix.el }}-${{ github.event_name == 'pull_request' && format('pr{0}', github.event.pull_request.number) || 'release' }}
          path: dist/*.rpm

  release:
    name: Release
    needs: build
    runs-on: ubuntu-latest
    if: startsWith(github.ref, 'refs/tags/') || github.event_name == 'workflow_dispatch'

    steps:
      - name: Checkout source (for tag fallback)
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Resolve release tag
        id: resolve_tag
        run: |
          TAG=""
          if [ "${GITHUB_REF#refs/tags/}" != "${GITHUB_REF}" ]; then
            TAG="${GITHUB_REF#refs/tags/}"
          elif [ -n "${{ github.event.inputs.version }}" ]; then
            TAG="${{ github.event.inputs.version }}"
          else
            git config --global --add safe.directory "$GITHUB_WORKSPACE"
            TAG="$(git tag --list 'v*' --sort=-v:refname | head -n 1 || true)"
          fi

          echo "tag_name=${TAG}" >> "$GITHUB_OUTPUT"
          if [ -n "${TAG}" ]; then
            echo "do_release=true" >> "$GITHUB_OUTPUT"
          else
            echo "do_release=false" >> "$GITHUB_OUTPUT"
          fi

      - name: Download EL9 artifacts
        if: steps.resolve_tag.outputs.do_release == 'true'
        uses: actions/download-artifact@v8
        with:
          name: rpm-el9-release
          path: dist

      - name: Download EL10 artifacts
        if: steps.resolve_tag.outputs.do_release == 'true'
        uses: actions/download-artifact@v8
        with:
          name: rpm-el10-release
          path: dist

      - name: Create GitHub Release
        if: steps.resolve_tag.outputs.do_release == 'true'
        uses: softprops/action-gh-release@v3
        with:
          tag_name: ${{ steps.resolve_tag.outputs.tag_name }}
          target_commitish: ${{ github.sha }}
          files: dist/*.rpm
          draft: true
          prerelease: ${{ contains(steps.resolve_tag.outputs.tag_name, '-rc') || contains(steps.resolve_tag.outputs.tag_name, '-beta') || contains(steps.resolve_tag.outputs.tag_name, '-alpha') }}
          generate_release_notes: false
          body: |
            ## :tada: AlmaLinux Creative Installer ${{ steps.resolve_tag.outputs.tag_name }}

            ### Highlights
            - (fill me in)

            ### Assets
            - EL9 RPM (Qt5 / PyQt5)
            - EL10 RPM (Qt6 / PyQt6)

  pr-beta-comment:
    name: Comment beta RPM location on PR
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'documentation')

    steps:
      - name: Post new comment with beta RPM download link
        uses: marocchino/sticky-pull-request-comment@v3
        with:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          header: beta-rpm
          recreate: true
          message: |
            ✅ Beta RPMs are ready for commit `${{ github.sha }}`.

            Download them from this run's artifacts:
            https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}#artifacts

            Expected artifact names:
            - `rpm-el9-pr${{ github.event.pull_request.number }}`
            - `rpm-el10-pr${{ github.event.pull_request.number }}`
