name: Update RPM Repository

on:
  release:
    types: [published]

jobs:
  update-rpm:
    name: Update RPM repository
    runs-on: ubuntu-latest

    steps:
      - name: Get release version
        id: version
        run: |
          version="${GITHUB_REF_NAME#v}"
          echo "version=$version" >> "$GITHUB_OUTPUT"

      - name: Download .rpm assets from release
        env:
          GH_TOKEN: ${{ github.token }}
        run: |
          mkdir -p /tmp/rpms
          gh release download "$GITHUB_REF_NAME" \
            --repo "$GITHUB_REPOSITORY" \
            --pattern "*.rpm" \
            --dir /tmp/rpms
          ls -la /tmp/rpms/

      - name: Checkout RPM repo
        uses: actions/checkout@v4
        with:
          repository: skyline69/rpm
          token: ${{ secrets.RPM_REPO_TOKEN }}
          path: rpm-repo
          ref: gh-pages

      - name: Import GPG key
        run: |
          echo "${{ secrets.RPM_GPG_PRIVATE_KEY }}" | gpg --batch --import

      - name: Update RPM repository
        run: |
          sudo apt-get update && sudo apt-get install -y createrepo-c rpm

          cd rpm-repo
          mkdir -p packages

          # Copy new RPMs
          cp /tmp/rpms/*.rpm packages/

          # Sign RPMs
          echo "%_gpg_name skyline69" > ~/.rpmmacros
          for rpm in packages/*.rpm; do
            rpm --addsign "$rpm" || rpmsign --addsign "$rpm"
          done

          # Generate repo metadata
          createrepo_c packages/

          # Sign repo metadata
          gpg --batch --yes --armor --detach-sign packages/repodata/repomd.xml

          # Export public key
          gpg --batch --armor --export skyline69 > public.key

      - name: Commit and push
        working-directory: rpm-repo
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add -A
          git commit -m "agcp ${{ steps.version.outputs.version }}"
          git push
