name: Build and Release RaveOS ISO

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

jobs:
  build-iso:
    runs-on: iso-builder

    env:
      TMPDIR: ${{ github.workspace }}/.tmp
      GIT_TMPDIR: ${{ github.workspace }}/.tmp

    steps:
      - name: Checkout build repository
        uses: actions/checkout@v4

      - name: Prepare temp directories (NO /tmp usage)
        run: |
          mkdir -p "${GITHUB_WORKSPACE}/.tmp"
          df -h

      - name: Fix raveos-core-repo pacman repo (overwrite clean)
        run: |
          sudo sed -i '/^\[raveos-core-repo\]/,/^$/d' /etc/pacman.conf
          cat <<'EOF' | sudo tee -a /etc/pacman.conf
          [raveos-core-repo]
          SigLevel = Never TrustAll
          Server = https://page.rp1.hu/x86_64/
          EOF

      - name: Update pacman databases
        run: sudo pacman -Sy --noconfirm

      - name: Verify archiso
        run: mkarchiso --version

      - name: Pre-build runner consistency check
        run: |
          IGNORE=$(grep '^IgnorePkg' /etc/pacman.conf | sed 's/IgnorePkg\s*=\s*//' | tr ' ' '\n' | tr ',' '\n')
          BROKEN=0

          while IFS= read -r line; do
            pkg=$(echo "$line" | awk '{print $1}')
            echo "$IGNORE" | grep -qx "$pkg" && continue
            installed=$(echo "$line" | awk '{print $2}')
            available=$(pacman -Si "$pkg" 2>/dev/null | grep '^Version' | head -1 | awk '{print $3}')
            if [ -n "$available" ] && [ "$(vercmp "$installed" "$available")" -lt 0 ]; then
              echo "VERZIO ELTER: $pkg | runner: $installed | repo: $available"
              BROKEN=1
            fi
          done < <(pacman -Q)

          if [ "$BROKEN" -eq 1 ]; then
            echo "HIBA: A runner csomagjai elternek a repotol. Frissitsd: sudo pacman -Syu"
            exit 1
          fi
          echo "Runner konzisztencia ellenorzes: OK"

      - name: Setup Chaotic-AUR
        run: |
          if [ ! -f /etc/pacman.d/chaotic-mirrorlist ]; then
            sudo mkdir -p /etc/pacman.d
            echo 'Server = https://cdn-mirror.chaotic.cx/$repo/$arch' | sudo tee /etc/pacman.d/chaotic-mirrorlist
            sudo pacman-key --recv-key 3056513887B78AEB --keyserver keyserver.ubuntu.com || true
            sudo pacman-key --lsign-key 3056513887B78AEB || true
            sudo pacman -U --noconfirm \
              https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-keyring.pkg.tar.zst \
              https://cdn-mirror.chaotic.cx/chaotic-aur/chaotic-mirrorlist.pkg.tar.zst || true
          fi

      - name: Build ISO
        run: |
          chmod +x ./build.sh
          sudo ./build.sh

      - name: Check build output
        run: |
          ls -lh output/*.iso

      - name: Check ISO for broken library links
        run: |
          sudo modprobe loop || true
          ISO_FILE=$(ls output/*.iso | head -1)
          MOUNT_DIR=$(mktemp -d)

          if ! sudo mount -o loop,ro "$ISO_FILE" "$MOUNT_DIR" 2>/dev/null; then
            echo "FIGYELMEZETES: ISO mountolas sikertelen (loop eszkoz nem elerheto), ldd ellenorzes kihagyva"
            rmdir "$MOUNT_DIR"
            exit 0
          fi

          BROKEN=0
          while IFS= read -r bin; do
            result=$(sudo chroot "$MOUNT_DIR" ldd "${bin#$MOUNT_DIR}" 2>/dev/null | grep "not found" || true)
            if [ -n "$result" ]; then
              echo "TOROTT: $bin"
              echo "$result"
              BROKEN=1
            fi
          done < <(find "$MOUNT_DIR" -type f \( -name "*.so*" -o -perm /111 \) 2>/dev/null | xargs -r file 2>/dev/null | grep ELF | cut -d: -f1)

          sudo umount "$MOUNT_DIR"
          rmdir "$MOUNT_DIR"

          if [ "$BROKEN" -eq 1 ]; then
            echo "HIBA: Torott library linkek az ISO-ban. Build leallitva."
            exit 1
          fi
          echo "ISO library ellenorzes: OK"

      - name: Create Forgejo Release and upload ISO
        run: |
          set -e

          ISO_FILE=$(ls output/*.iso | head -1)
          ISO_NAME=$(basename "$ISO_FILE")
          ISO_SIZE=$(du -h "$ISO_FILE" | cut -f1)
          ISO_SHA256=$(sha256sum "$ISO_FILE" | cut -d' ' -f1)
          BUILD_DATE=$(date '+%Y-%m-%d %H:%M:%S')
          COMMIT_SHORT=${GITHUB_SHA::7}
          TAG="v$(date '+%Y.%m.%d')-${COMMIT_SHORT}"

          RELEASE_BODY="Build Date: ${BUILD_DATE}
          Filename: ${ISO_NAME}
          Size: ${ISO_SIZE}
          SHA256: ${ISO_SHA256}
          Source Commit: ${COMMIT_SHORT}

          Verification:
          echo \"${ISO_SHA256}  ${ISO_NAME}\" | sha256sum -c"

          RELEASE=$(curl -s -X POST "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d "{\"tag_name\":\"${TAG}\",\"name\":\"RaveOS ${TAG}\",\"body\":$(echo "$RELEASE_BODY" | python3 -c 'import sys,json; print(json.dumps(sys.stdin.read()))'),\"draft\":false,\"prerelease\":false}")

          RELEASE_ID=$(echo "$RELEASE" | python3 -c "import sys,json; print(json.load(sys.stdin)['id'])")
          echo "Release ID: $RELEASE_ID"

          echo "ISO feltoltes indul: $ISO_NAME ($ISO_SIZE)"
          UPLOAD=$(curl -f --progress-bar -X POST "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases/${RELEASE_ID}/assets" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
            -F "attachment=@${ISO_FILE}")
          echo "Upload valasz: $UPLOAD"

          echo "Release feltoltve: https://git.rp1.hu/RaveOS/RaveOS-Releases/releases/tag/${TAG}"

          RELEASES=$(curl -s "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases?limit=50" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}")

          echo "$RELEASES" | python3 -c "
import sys, json
releases = json.load(sys.stdin)
releases.sort(key=lambda r: r['id'], reverse=True)
for r in releases[3:]:
    print(r['id'], r['tag_name'])
" | while read id tag; do
            curl -s -X DELETE "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases/$id" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}"
            curl -s -X DELETE "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/tags/$tag" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}"
            echo "Regi release torolve: $tag"
          done

      - name: Cleanup (SAFE)
        if: always()
        run: |
          sudo umount -R "${GITHUB_WORKSPACE}/work" 2>/dev/null || true
          sudo umount -R "${GITHUB_WORKSPACE}/output" 2>/dev/null || true
          sudo rm -rf "${GITHUB_WORKSPACE}/work"
          sudo rm -rf "${GITHUB_WORKSPACE}/output"
          sudo rm -rf "${GITHUB_WORKSPACE}/.tmp"
          sudo rm -rf /var/cache/pacman/pkg/*
          df -h
