# Nach jedem Push auf main, der VERSION ändert: omninx_pack= in OmniNX-Downloader
# include/updater/RELEASE.ini auf denselben Wert setzen und committen.
#
# Voraussetzung: Repository-Secret DOWNLOADER_SYNC_TOKEN
#   — Personal Access Token (Gitea) mit repo: Inhalt „schreiben“ auf
#     OmniNX/OmniNX-Downloader (nicht der eingebaute GITHUB_TOKEN dieses Repos).
# Commit-Nachricht enthält [skip ci], damit der Downloader keine Endlosschleife startet,
# falls dort Workflows auf jeden Push reagieren.

name: Sync omninx_pack to OmniNX-Downloader

on:
  push:
    branches:
      - main
    paths:
      - 'VERSION'
  workflow_dispatch:

jobs:
  sync-release-ini:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout OmniNX
        uses: actions/checkout@v3

      - name: Read VERSION
        id: pack
        run: |
          v=$(python3 -c "print(open('VERSION', encoding='utf-8').read().strip())")
          echo "value=$v" >> "$GITHUB_OUTPUT"

      - name: Checkout OmniNX-Downloader
        uses: actions/checkout@v3
        with:
          repository: OmniNX/OmniNX-Downloader
          ref: main
          path: omninx-downloader
          token: ${{ secrets.DOWNLOADER_SYNC_TOKEN }}

      - name: Set omninx_pack in RELEASE.ini
        env:
          PACK_VER: ${{ steps.pack.outputs.value }}
        run: |
          python3 <<'PY'
          import os
          import pathlib
          import re

          ver = os.environ["PACK_VER"].strip()
          p = pathlib.Path("omninx-downloader/include/updater/RELEASE.ini")
          text = p.read_text(encoding="utf-8")
          new, n = re.subn(
              r"^omninx_pack=.*$",
              f"omninx_pack={ver}",
              text,
              count=1,
              flags=re.MULTILINE,
          )
          if n != 1:
              raise SystemExit(
                  f"RELEASE.ini: genau eine Zeile omninx_pack= erwartet, {n} ersetzt."
              )
          p.write_text(new, encoding="utf-8")
          PY

      - name: Commit and push
        env:
          PACK_VER: ${{ steps.pack.outputs.value }}
        run: |
          set -euo pipefail
          cd omninx-downloader
          git config user.name "gitea-actions[bot]"
          git config user.email "gitea-actions[bot]@local"
          git add include/updater/RELEASE.ini
          if git diff --staged --quiet; then
            echo "Bereits aktuell — kein Commit."
            exit 0
          fi
          git commit -m "chore: sync omninx_pack to ${PACK_VER} from OmniNX VERSION [skip ci]"
          git push
