name: Build raveos packages and publish to raveos-core-repo (SAFE)

on:
  push:
    branches: ["main"]
  workflow_dispatch:

concurrency:
  group: raveos-theme-module-build-publish
  cancel-in-progress: true

jobs:
  build:
    runs-on: iso-builder

    steps:
      - name: Checkout PKGBUILDs repo
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install build tools
        run: |
          set -euo pipefail
          sudo pacman -S --needed --noconfirm \
            base-devel git pacman-contrib cmake qt6-tools go cargo gtk4-layer-shell hyprland

      - name: Sync core repo from VPS (rsync pull)
        run: |
          set -euo pipefail
          RSYNC_SSH="ssh -p 2222 -i $HOME/.ssh/vps_backup_key -o StrictHostKeyChecking=no"
          rm -rf /tmp/raveos-core-repo
          mkdir -p /tmp/raveos-core-repo/x86_64
          rsync -az -e "$RSYNC_SSH" \
            root@10.66.66.1:/root/docker/repo/repo/x86_64/ /tmp/raveos-core-repo/x86_64/
          mkdir -p /tmp/builtpkgs

      - name: Import GPG signing key
        run: |
          set -euo pipefail
          export GNUPGHOME=/tmp/raveos-gnupg
          rm -rf "$GNUPGHOME"
          mkdir -m 700 "$GNUPGHOME"
          echo "${{ secrets.GPG_PRIVATE_KEY }}" | base64 -d | gpg --batch --import

      - name: Build raveos-calamares-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-calamares-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-calamares-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-calamares-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -f *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          cp -v raveos-calamares-theme-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-mirrorlist
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-mirrorlist
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-mirrorlist-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-mirrorlist ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -f *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          cp -v raveos-mirrorlist-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-calamares-module
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-calamares-module
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-calamares-module-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-calamares-module ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -f *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          cp -v raveos-calamares-module-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-calamares
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-calamares
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/calamares-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-calamares ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -f *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          PKG=$(ls -t *.pkg.tar.zst | grep -v -- '-debug-' | head -n 1)
          cp -v "$PKG" /tmp/builtpkgs/

      - name: Build raveos-keyring
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-keyring
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-keyring-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-keyring ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-keyring-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-sddm-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-sddm-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-sddm-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-sddm-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-sddm-theme-*.pkg.tar.zst /tmp/builtpkgs/
          # Azonnal telepitjuk is, mert meg nincs publikalva egy repoban sem
          # (a "Publish" lepes csak a legvegen fut) - a tobbi DE-tema csomag
          # makepkg -s hivasa igy fogja tudni feloldani a fuggoseget.
          sudo pacman -U --noconfirm build/raveos-sddm-theme-*.pkg.tar.zst

      - name: Build raveos-plasma-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-plasma-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-plasma-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-plasma-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-plasma-theme-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-gnome-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-gnome-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-gnome-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-gnome-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-gnome-theme-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-hyprland-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-hyprland-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-hyprland-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-hyprland-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-hyprland-theme-*.pkg.tar.zst /tmp/builtpkgs/
          rm -f /tmp/builtpkgs/raveos-hyprland-theme-debug-*.pkg.tar.zst || true

      - name: Build raveos-cosmic-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-cosmic-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-cosmic-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-cosmic-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-cosmic-theme-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-tools
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-tools
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-tools-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-tools ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-tools-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-app-installer
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-app-installer
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-app-installer-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-app-installer ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-app-installer-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-welcome
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-welcome
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-welcome-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-welcome ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf build || true
          makepkg -s --noconfirm -f
          cp -v build/raveos-welcome-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveos-plymouth-theme
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveos-plymouth-theme
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveos-plymouth-theme-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveos-plymouth-theme ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -f *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          cp -v raveos-plymouth-theme-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Build raveswitch
        run: |
          set -euo pipefail
          CORE="/tmp/raveos-core-repo/x86_64"
          cd raveswitch
          PKGVER=$(grep '^pkgver=' PKGBUILD | cut -d= -f2)
          PKGREL=$(grep '^pkgrel=' PKGBUILD | cut -d= -f2)
          if ls "$CORE/raveswitch-${PKGVER}-${PKGREL}-"*.pkg.tar.zst 2>/dev/null | grep -q .; then
            echo "raveswitch ${PKGVER}-${PKGREL} unchanged -> skip"
            exit 0
          fi
          rm -rf src pkg hyprland_raveswitch *.pkg.tar.zst || true
          makepkg -s --noconfirm -f
          cp -v raveswitch-*.pkg.tar.zst /tmp/builtpkgs/

      - name: Sign built packages
        run: |
          set -euo pipefail
          export GNUPGHOME=/tmp/raveos-gnupg
          BUILT=$(ls /tmp/builtpkgs/*.pkg.tar.zst 2>/dev/null || true)
          if [ -z "$BUILT" ]; then
            echo "Nincs csomag alairashoz -> kihagyva"
            exit 0
          fi
          for pkg in $BUILT; do
            gpg --batch --yes --pinentry-mode loopback \
                --passphrase "${{ secrets.GPG_PRIVATE_KEY_PASSPHRASE }}" \
                --local-user 25C7668F1235F5664F037671BDB2A9CE6EBFF113 \
                --detach-sign "$pkg"
            echo "Alairva: $(basename "$pkg")"
          done

      - name: Publish packages (repo-add + rsync push, only if changed)
        run: |
          set -euo pipefail

          CORE="/tmp/raveos-core-repo/x86_64"
          mkdir -p "$CORE"

          BUILT=$(ls /tmp/builtpkgs/*.pkg.tar.zst 2>/dev/null || true)
          if [ -z "$BUILT" ]; then
            echo "No packages built -> nem masolunk uj fajlt, de a db-t mindig ujraepitjuk (onjavito)"
          else
            for pkg in $BUILT; do
              PKGFILE=$(basename "$pkg")
              PKGNAME=$(echo "$PKGFILE" | sed 's/-[0-9][^-]*-[^-]*-[^-]*\.pkg\.tar\.zst$//')
              if [[ ! "$PKGNAME" =~ ^[a-zA-Z0-9_+-]+$ ]]; then
                echo "HIBA: Ervenytelen csomagnev: $PKGNAME -> skip"
                continue
              fi
              rm -f "$CORE/${PKGNAME}-"*.pkg.tar.zst* 2>/dev/null || true
              cp -v "$pkg" "$CORE/"
              [ -f "$pkg.sig" ] && cp -v "$pkg.sig" "$CORE/"
            done
          fi

          # Adatbazis ujraepitese HELYBEN (nincs tobbe kulon repo-add job/repo)
          # .xz celzunk (nem .gz), es minden CORE-beli csomagot atadunk a repo-add-nak.
          # A repo-add sajat "--sign"-ja gpg-agentre tamaszkodik jelszo nelkul -- ha
          # az agent cache hideg (pl. amikor nem epult uj csomag, igy a "Sign built
          # packages" lepes se futott le), a signeles nesztelenul elhasal (repo-add
          # csak warningot ir, a regi .sig marad, ami mar nem illik az uj tartalomhoz).
          # Ezert kulon, expliciten alairjuk a db/files fajlokat a jelszo megadasaval.
          export GNUPGHOME=/tmp/raveos-gnupg
          cd "$CORE"
          ALLPKGS=$(ls *.pkg.tar.zst)
          repo-add raveos-core-repo.db.tar.xz $ALLPKGS

          for f in raveos-core-repo.db.tar.xz raveos-core-repo.files.tar.xz; do
            gpg --batch --yes --pinentry-mode loopback \
                --passphrase "${{ secrets.GPG_PRIVATE_KEY_PASSPHRASE }}" \
                --local-user 25C7668F1235F5664F037671BDB2A9CE6EBFF113 \
                --detach-sign --no-armor -o "$f.sig" "$f"
          done
          ln -sf raveos-core-repo.db.tar.xz.sig raveos-core-repo.db.sig
          ln -sf raveos-core-repo.files.tar.xz.sig raveos-core-repo.files.sig

          rm -f raveos-core-repo.db.tar.gz* raveos-core-repo.files.tar.gz* 2>/dev/null || true

          # Vissza-szinkron a VPS-re (torli, ami helyben mar nincs, pl. regi verziok)
          RSYNC_SSH="ssh -p 2222 -i $HOME/.ssh/vps_backup_key -o StrictHostKeyChecking=no"
          rsync -az --delete -e "$RSYNC_SSH" \
            "$CORE/" root@10.66.66.1:/root/docker/repo/repo/x86_64/

          echo "::notice title=Published packages::rsync-alapu publikalas kesz"

      - name: Mirror raveos-core-repo to GitHub Releases
        if: always()
        run: |
          set -euo pipefail
          REPO="/tmp/raveos-core-repo"
          [ -d "$REPO/x86_64" ] || { echo "Nincs mit tükrözni -> kihagyva"; exit 0; }

          # A "Publish" lepes mar szinkron modon, ugyanebben a jobban rsync-elte
          # ki a friss allapotot a VPS-re - nincs tobbe kulon aszinkron repo-add
          # job/webhook-lanc, amire varni kellene.

          OWNER="rave-os"
          GH_REPO="RaveOS-core-repo-mirror"
          TAG="core-repo-x86_64"
          API="https://api.github.com/repos/${OWNER}/${GH_REPO}"

          TOKEN="${{ secrets.GH_MIRROR_TOKEN }}"

          release_json=$(curl -sf -H "Authorization: Bearer ${TOKEN}" \
            "${API}/releases/tags/${TAG}") || { echo "HIBA: nincs '${TAG}' release a GitHub repoban -> kihagyva"; exit 0; }
          release_id=$(echo "$release_json" | jq -r .id)
          existing_assets=$(echo "$release_json" | jq -r '.assets[] | "\(.id)\t\(.name)"')

          cd "$REPO/x86_64"

          # 1) regi verziojú csomag-assetek torlese verzio-prefix alapjan
          #    (a fajlnevek tartalmazzak a pkgver-pkgrel-t, ezert egy verziofrissites
          #    uj fajlnevet ad - enelkul a regi verziok orokre felhalmozodnanak)
          for f in *.pkg.tar.zst; do
            [ -f "$f" ] || continue
            pkgname=$(echo "$f" | sed -E 's/-[0-9][^-]*-[^-]*-[^-]*\.pkg\.tar\.zst$//')
            [ -n "$pkgname" ] || continue
            while IFS=$'\t' read -r aid aname; do
              [ -n "$aid" ] || continue
              case "$aname" in
                "${pkgname}-"*.pkg.tar.zst | "${pkgname}-"*.pkg.tar.zst.sig)
                  if [ "$aname" != "$f" ] && [ "$aname" != "${f}.sig" ]; then
                    curl -sf -X DELETE -H "Authorization: Bearer ${TOKEN}" \
                      "${API}/releases/assets/${aid}" || true
                    echo "torolve (regi verzio): $aname"
                  fi
                  ;;
              esac
            done <<< "$existing_assets"
          done

          # friss asset-lista a torlesek utan
          existing_assets=$(curl -sf -H "Authorization: Bearer ${TOKEN}" \
            "${API}/releases/${release_id}" | jq -r '.assets[] | "\(.id)\t\(.name)"')

          # 2) minden aktualis fajl feltoltese (azonos nevu regi peldany cserevel)
          for f in *; do
            [ -f "$f" ] || continue
            asset_id=$(echo "$existing_assets" | awk -F'\t' -v n="$f" '$2==n {print $1}')
            if [ -n "$asset_id" ]; then
              curl -sf -X DELETE -H "Authorization: Bearer ${TOKEN}" \
                "${API}/releases/assets/${asset_id}" || true
            fi
            curl -sf -X POST \
              -H "Authorization: Bearer ${TOKEN}" \
              -H "Content-Type: application/octet-stream" \
              --data-binary "@${f}" \
              "https://uploads.github.com/repos/${OWNER}/${GH_REPO}/releases/${release_id}/assets?name=${f}" \
              || echo "HIBA: ${f} feltoltese sikertelen"
          done
          echo "::notice title=GitHub mirror::Kesz"

      - name: Cleanup (SAFE)
        if: always()
        run: |
          gpgconf --homedir /tmp/raveos-gnupg --kill gpg-agent || true
          sudo rm -rf /tmp/raveos-gnupg || true
          sudo rm -rf /tmp/builtpkgs || true
          sudo rm -rf /tmp/raveos-core-repo || true
          sudo rm -rf /var/cache/pacman/pkg/* || true
          df -h
