name: Hyperion DNF Build

on:
  # Reusable from nightly and push
  workflow_call:
    inputs:
      head_sha:
        type: string
        description: The branch, tag or SHA to checkout
        default: "master"
        required: false
      nightly:
        type: boolean
        description: Nightly build
        default: false
        required: false
      publish:
        type: boolean
        description: Publish packages
        default: false
        required: false
  # For running the workflow manually via GitHub Actions tab
  workflow_dispatch:
    inputs:
      head_sha:
        type: string
        description: The branch, tag or SHA to checkout
        default: "master"
        required: false
      nightly:
        type: boolean
        description: Nightly build
        default: false
        required: false
      publish:
        type: boolean
        description: Publish packages
        default: false
        required: false

env:
  ghcr: hyperion-project

jobs:
  build:
    name: ๐Ÿง ${{ matrix.os.distribution }} ${{ matrix.os.version }} (${{ matrix.architecture[0] }})
    runs-on: ubuntu-latest
    strategy:
      fail-fast: false
      matrix:
        os: [
          { distribution: Fedora, version: 37 },
          { distribution: Fedora, version: 38 },
          { distribution: Fedora, version: 39 },
          { distribution: Fedora, version: 40 }
        ]
        architecture: [
          [ amd64, linux/amd64 ]
        ]

    steps:
      - name: โฌ‡ Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.head_sha || github.event.client_payload.head_sha }}
          submodules: recursive

      - name: ๐Ÿ”ง Prepare
        run: |
          echo '::group::Checking the version number'
            if [[ "${{ inputs.nightly }}" = true ]]; then
              echo VERSION=$(tr -d '\n' < .version)+nightly$(date '+%Y%m%d')$(git rev-parse --short HEAD | sed s/-/_/g) >> $GITHUB_ENV
            else
              echo VERSION=$(tr -d '\n' < .version | sed s/-/_/g) >> $GITHUB_ENV
            fi
          echo '::endgroup::'

      - name: ๐Ÿ› ๏ธ Setup QEMU
        uses: docker/setup-qemu-action@v3

      - name: ๐Ÿ‘ท Build
        shell: bash
        run: |
          echo '::group::Set distribution name to lower case'
            DISTRIBUTION=$(echo '${{ matrix.os.distribution }}' | tr '[:upper:]' '[:lower:]')
          echo '::endgroup::'

          echo '::group::Building Hyperion'
            mkdir -p "${GITHUB_WORKSPACE}/deploy"
            docker run --rm --platform=${{ matrix.architecture[1] }} \
              -w "/root" \
              -v "${GITHUB_WORKSPACE}/deploy:/deploy" \
              -v "${GITHUB_WORKSPACE}:/root/hyperion.ng:rw" \
              ghcr.io/${{ env.ghcr }}/${DISTRIBUTION}:${{ matrix.os.version }} \
              /bin/bash -c "tar -czf rpmbuild/SOURCES/hyperion.ng.tar.gz hyperion.ng/ && \
              cp -f hyperion.ng/rpmbuild/hyperion.spec.in rpmbuild/SPECS/hyperion.spec && \
              rpmbuild -ba --define '_version ${{ env.VERSION }}' rpmbuild/SPECS/hyperion.spec --clean && \
              cp -fv rpmbuild/RPMS/$(uname -m)/hyperion* /deploy"
          echo '::endgroup::'
        env:
          ACTOR: "Hyperion Project <admin@hyperion-project.org>"
          COMMIT_MESSAGE: ${{ github.event.commits[0].message }}

      - name: ๐Ÿ“ฆ Upload
        if: ${{ inputs.publish }}
        uses: actions/upload-artifact@v3
        with:
          path: deploy
          retention-days: 1

  publish:
    name: ๐Ÿš€ Publish RPM packages
    if: ${{ github.repository == 'hyperion-project' && inputs.publish }}
    needs: [build]
    runs-on: ubuntu-latest
    container:
      image: fedora
    steps:
      - name: โฌ‡ Checkout
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.head_sha || github.event.client_payload.head_sha }}

      - name: ๐Ÿ”‘ GPG Import
        id: import_gpg
        if: ${{ env.SECRET_GPG_KEY != null }}
        uses: crazy-max/ghaction-import-gpg@v5
        with:
          gpg_private_key: ${{ secrets.GPG_KEY }}
        env:
          SECRET_GPG_KEY: ${{ secrets.GPG_KEY }}

      - name: ๐Ÿ’พ Artifact download
        uses: actions/download-artifact@v3

      - name: ๐Ÿ”ง Prepare
        if: ${{ env.SECRET_DNF_REPO_NIGHTLY != null && env.SECRET_DNF_REPO != null }}
        run: |
          echo '::group::Install createrepo & rpm-sign'
            dnf install createrepo rpm-sign -y
          echo '::endgroup::'

          echo '::group::Make folders, sign/copy packages and create metadata/manifest files'
            mkdir rpm/
            gpg --armor --output hyperion.pub.key --export 'admin@hyperion-project.org'
            rpm --import hyperion.pub.key
            channel=$([ "${{ inputs.nightly }}" = true ] && echo "Nightly" || echo "Stable")
            declare -A distArray=([fc]=fedora [el]=rhel)
            for file in artifact/hyperion-*.rpm; do
              if [ -f "$file" ]; then
                dist_ver_arch=$(basename -- "$file")
                dist_ver_arch=${dist_ver_arch%.*}
                dist_ver=${dist_ver_arch%.*}
                dist_ver=${dist_ver##*.}
                [ -z "${dist_ver:0:2}" ] && continue
                rpm=rpm/${distArray[${dist_ver:0:2}]}/${dist_ver:2}/${dist_ver_arch##*.}
                mkdir -p $rpm/ && cp $file $rpm/
                rpm --define "_gpg_name ${{ steps.import_gpg.outputs.keyid }}" --addsign $rpm/*.rpm
                rpm --checksig $rpm/*.rpm
                createrepo $rpm/
                gpg --yes --detach-sign --armor $rpm/repodata/repomd.xml
                sed -r "s/@CHANNEL@/${channel}/g; s/@DIST@/${distArray[${dist_ver:0:2}]}/g; s/@ARCH@/${dist_ver_arch##*.}/g" ${GITHUB_WORKSPACE}/rpmbuild/hyperion.repo.in > rpm/${distArray[${dist_ver:0:2}]}/hyperion.repo
              fi
            done
          echo '::endgroup::'

          echo '::group::Set server directory'
            if [[ "${{ inputs.nightly }}" = true ]]; then
              echo "SERVER_DIR=${{ secrets.DNF_REPO_NIGHTLY }}" >> $GITHUB_ENV
            else
              echo "SERVER_DIR=${{ secrets.DNF_REPO }}" >> $GITHUB_ENV
            fi
          echo '::endgroup::'
        env:
          SECRET_DNF_REPO_NIGHTLY: ${{ secrets.DNF_REPO_NIGHTLY }}
          SECRET_DNF_REPO: ${{ secrets.DNF_REPO }}

      - name: ๐Ÿ“ฆ Upload
        if: ${{ env.SECRET_REPO_USER != null && env.SECRET_REPO_PASSWORD != null && env.SERVER_DIR != null }}
        uses: SamKirkland/FTP-Deploy-Action@v4.3.4
        with:
          server: releases.hyperion-project.org
          username: ${{ secrets.REPO_USER }}
          password: ${{ secrets.REPO_PASSWORD }}
          server-dir: ${{ env.SERVER_DIR }}
          local-dir: "./rpm/"
          dangerous-clean-slate: true
        env:
          SECRET_REPO_USER: ${{ secrets.REPO_USER }}
          SECRET_REPO_PASSWORD: ${{ secrets.REPO_PASSWORD }}

      - name: ๐Ÿงน Cleanup
        uses: geekyeggo/delete-artifact@v2
        with:
          name: artifact
          failOnError: false