name: Update pacman repo DB (repo-add)

on:
  push:
    tags:
      - "v*"
      - "vrepo-*"
  workflow_dispatch:

jobs:
  repoadd:
    runs-on: iso-builder

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

      - name: Install repo-add (pacman-contrib)
        run: |
          sudo pacman -S --needed --noconfirm pacman-contrib

      - name: Rebuild repo DB files
        run: |
          set -euo pipefail

          REPO_NAME="raveos-core-repo"

          if [ ! -d "x86_64" ]; then
            echo "ERROR: x86_64 directory not found!"
            exit 1
          fi

          cd x86_64

          rm -f "${REPO_NAME}.db" \
                "${REPO_NAME}.files" \
                "${REPO_NAME}.db.tar.xz" \
                "${REPO_NAME}.files.tar.xz" \
                "${REPO_NAME}.db.tar.xz.old" \
                "${REPO_NAME}.files.tar.xz.old" || true

          repo-add "${REPO_NAME}.db.tar.xz" ./*.pkg.tar.zst

          ln -sf "${REPO_NAME}.db.tar.xz" "${REPO_NAME}.db"
          ln -sf "${REPO_NAME}.files.tar.xz" "${REPO_NAME}.files"

          echo "=== DB files created ==="
          ls -la | grep -E "${REPO_NAME}\.(db|files)"

      - name: Commit and push updated DB files (to main)
        run: |
          set -euo pipefail

          cd "${GITHUB_WORKSPACE}"

          git config user.name "Forgejo Actions"
          git config user.email "actions@forgejo.local"

          git fetch origin main
          git checkout -B main origin/main

          git add x86_64/raveos-core-repo.db* x86_64/raveos-core-repo.files* || true

          if git diff --staged --quiet; then
            echo "No DB changes, nothing to commit."
            exit 0
          fi

          git commit -m "Update pacman repo DB (repo-add)"
          git push origin main
      - name: Cleanup (force unmount + delete)
        if: always()
        run: |
          echo "=== Disk before cleanup ==="
          df -h

          echo "=== Unmount leftover archiso mounts ==="
          sudo umount -R "${GITHUB_WORKSPACE}/work" 2>/dev/null || true
          sudo umount -R "${GITHUB_WORKSPACE}/output" 2>/dev/null || true

          echo "=== Remove build dirs ==="
          sudo rm -rf "${GITHUB_WORKSPACE}/work" || true
          sudo rm -rf "${GITHUB_WORKSPACE}/output" || true

          echo "=== Clear pacman cache ==="
          sudo rm -rf /var/cache/pacman/pkg/* || true

          echo "=== Disk after cleanup ==="
          df -h