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: |
          set -euo pipefail
          mkdir -p "${GITHUB_WORKSPACE}/.tmp"
          df -h

      - name: Fix raveos-core-repo pacman repo (overwrite clean)
        run: |
          set -euo pipefail
          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: Sync and update runner
        run: |
          set -euo pipefail
          sudo pacman -Sy --noconfirm
          if pacman -Qu 2>/dev/null | grep -q .; then
            echo "Elavult csomagok talalhatok, auto-frissites indul..."
            sudo pacman -Su --noconfirm
            echo "Runner auto-frissites: OK"
          else
            echo "Runner konzisztencia ellenorzes: OK"
          fi

      - name: Verify archiso
        run: pacman -Q archiso

      - name: Setup Chaotic-AUR
        run: |
          set -euo pipefail
          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: Setup RaveOS signing key
        run: |
          set -euo pipefail
          cat <<'RAVEOSKEY' | sudo pacman-key --add -
          -----BEGIN PGP PUBLIC KEY BLOCK-----

[encoded data, 4425 characters]
          ibVZLr5g97pSMBQUv/dO6I+jfPtqITpDupTdDgg=
          =WGkj
          -----END PGP PUBLIC KEY BLOCK-----
          RAVEOSKEY
          sudo pacman-key --lsign-key 25C7668F1235F5664F037671BDB2A9CE6EBFF113

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

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

      - name: Check ISO for broken library links
        run: |
          set -euo pipefail
          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: Upload ISO to release server
        run: |
          set -euo pipefail
          ISO_FILE=$(ls output/*.iso | head -1)
          ISO_NAME=$(basename "$ISO_FILE")

          mkdir -p ~/.ssh
          echo "${{ secrets.VPS_RELEASE_KEY }}" > ~/.ssh/vps_release_key
          chmod 600 ~/.ssh/vps_release_key

          # Új ISO feltöltése
          scp -i ~/.ssh/vps_release_key -P ${{ secrets.VPS_PORT }} -o StrictHostKeyChecking=no \
            "$ISO_FILE" "${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }}:${{ secrets.VPS_RELEASES_PATH }}/${ISO_NAME}"

          # 3-nál régebbi ISO-k törlése a VPS-ről
          ssh -i ~/.ssh/vps_release_key -p ${{ secrets.VPS_PORT }} -o StrictHostKeyChecking=no \
            ${{ secrets.VPS_USER }}@${{ secrets.VPS_HOST }} "ls -t ${{ secrets.VPS_RELEASES_PATH }}/*.iso 2>/dev/null | tail -n +4 | xargs -r rm -f"

          echo "ISO feltoltve: https://release.rp1.hu/${ISO_NAME}"
          echo "ISO_NAME=${ISO_NAME}" >> "$GITHUB_ENV"

      - name: Create Forgejo Release with external link
        run: |
          set -euo pipefail

          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 -f -s --retry 3 --retry-delay 5 \
            -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'])")
          [[ "$RELEASE_ID" =~ ^[0-9]+$ ]] || { echo "HIBA: Ervenytelen RELEASE_ID: $RELEASE_ID"; exit 1; }
          echo "Release ID: $RELEASE_ID"

          # External link hozzáadása attachment helyett
          curl -f -s --retry 3 \
            -X POST "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases/${RELEASE_ID}/assets?external_url=https://release.rp1.hu/${ISO_NAME}" \
            -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}" \
            -F "name=${ISO_NAME}"
          echo "External link hozzaadva: https://release.rp1.hu/${ISO_NAME}"

          echo "Release kesz: https://git.rp1.hu/RaveOS/RaveOS-Releases/releases/tag/${TAG}"
          echo "TAG=${TAG}" >> "$GITHUB_ENV"
          echo "ISO_SHA256=${ISO_SHA256}" >> "$GITHUB_ENV"

          # Regi release-ek torlese (3-nal tobbet nem tartunk)
          RELEASES=$(curl -f -s --retry 3 --retry-delay 5 \
            "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); [print(r['id'],r['tag_name']) for r in releases[3:]]" | while IFS=' ' read -r id tag; do
            curl -f -s --retry 3 -X DELETE "https://git.rp1.hu/api/v1/repos/RaveOS/RaveOS-Releases/releases/$id" \
              -H "Authorization: token ${{ secrets.RELEASE_TOKEN }}"
            curl -f -s --retry 3 -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: Update Shlink short URL
        if: always()
        env:
          SHLINK_URL: ${{ secrets.SHLINK_URL }}
          SHLINK_API_KEY: ${{ secrets.SHLINK_API_KEY }}
          ISO_NAME: ${{ env.ISO_NAME }}
        run: |
          set -euo pipefail
          if [ -z "${SHLINK_URL:-}" ] || [ -z "${SHLINK_API_KEY:-}" ]; then
            echo "Shlink nincs beallitva, kihagyva"
            exit 0
          fi
          ISO_NAME="${ISO_NAME:-unknown}"
          LONG_URL="https://release.rp1.hu/${ISO_NAME}"

          curl -s -X POST "${SHLINK_URL}/rest/v3/short-urls" \
            -H "X-Api-Key: ${SHLINK_API_KEY}" \
            -H "Content-Type: application/json" \
            -d "{\"longUrl\":\"${LONG_URL}\",\"customSlug\":\"raveos-download\",\"findIfExists\":true}" || true

          curl -s -X PATCH "${SHLINK_URL}/rest/v3/short-urls/raveos-download" \
            -H "X-Api-Key: ${SHLINK_API_KEY}" \
            -H "Content-Type: application/json" \
            -d "{\"longUrl\":\"${LONG_URL}\"}" || true

      - name: Discord notification
        if: always()
        env:
          DISCORD_WEBHOOK: ${{ secrets.DISCORD_WEBHOOK }}
          TAG: ${{ env.TAG }}
          ISO_NAME: ${{ env.ISO_NAME }}
          ISO_SHA256: ${{ env.ISO_SHA256 }}
        run: |
          set -euo pipefail
          if [ -z "${DISCORD_WEBHOOK:-}" ]; then
            echo "DISCORD_WEBHOOK nincs beallitva, ertesites kihagyva"
            exit 0
          fi
          TAG="${TAG:-unknown}"
          ISO_NAME="${ISO_NAME:-unknown}"
          ISO_SHA256="${ISO_SHA256:-n/a}"

          bash scripts/discord-notify.sh "${DISCORD_WEBHOOK}" "${TAG}" "${ISO_NAME}" "${ISO_SHA256}"

      - name: Cleanup (SAFE)
        if: always()
        run: |
          rm -f ~/.ssh/vps_release_key
          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
