name: CI | Publish github repository package
on:
  push:
    branches: ['master']
  pull_request:
    branches: ['master']
  workflow_dispatch:
    inputs:
      conf_id:
        description: 'Conf id of the canonical engine github package repo (engine-ghpkg-<conf_id>)'
        required: false
        default: 'cyberia'
      change_summary:
        description: 'Change summary to commit: its JSON, or a plain message'
        required: false
        default: ''
permissions:
  contents: write
  packages: write
  id-token: write
jobs:
  pwa-microservices-template-ghpk:
    if: >-
      (github.repository == 'underpostnet/pwa-microservices-template') &&
       (
         startsWith(github.event.head_commit.message, 'ci(package-pwa-microservices-template-ghpkg)')
         || 
         github.event_name == 'workflow_dispatch'
       )
    name: Update github repo package Jobs
    runs-on: ubuntu-latest
    container:
      image: quay.io/rockylinux/rockylinux:9
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      # Install git first. Checkout without git downloads an archive that has no .git.
      - name: Install required packages
        run: |
          dnf install -y sudo tar gzip bzip2 git
          dnf install -y curl --allowerasing

      - name: Clone repository
        uses: actions/checkout@v7

      # The checkout belongs to another user than the container root. Git refuses it without this.
      - name: Trust the checkout in git
        run: git config --global --add safe.directory '*'

      - name: Install Node.js
        run: |
          curl -fsSL https://rpm.nodesource.com/setup_24.x | bash -
          dnf install nodejs -y

      - name: Install dependencies and set repo configuration
        run: |
          npm install
          node ./bin package --rename @underpostnet/underpost
          node ./bin package --set-repo underpostnet/pwa-microservices-template-ghpkg

      # Placed after the install because it resolves the payload through the CLI, which needs the
      # dependencies. The push that triggers this job carries the payload the engine propagated.
      - name: Resolve the change summary
        env:
          # Never interpolated into the script: a change summary is free text, which a shell
          # expansion would corrupt or execute.
          CHANGE_SUMMARY: ${{ github.event.head_commit.message }}
        run: |
          CHANGE_SUMMARY=$(node ./bin release --change-summary --fallback "update package")
          CHANGE_MESSAGE=$(CHANGE_SUMMARY="$CHANGE_SUMMARY" node ./bin release --change-summary --format message)
          {
            echo "CHANGE_SUMMARY=$CHANGE_SUMMARY"
            echo "CHANGE_MESSAGE<<CHANGE_SUMMARY_EOF"
            echo "$CHANGE_MESSAGE"
            echo "CHANGE_SUMMARY_EOF"
          } >> "$GITHUB_ENV"
          echo "[INFO] Change summary: $CHANGE_SUMMARY"

      - name: Set git global credentials
        env:
          GITHUB_USERNAME: ${{ github.repository_owner }}
          GITHUB_EMAIL: ${{ secrets.GIT_EMAIL }}
        run: |
          : "${GITHUB_EMAIL:?the GIT_EMAIL Actions secret is not set}"
          git config --global credential.helper ""
          git config --global user.name "$GITHUB_USERNAME"
          git config --global user.email "$GITHUB_EMAIL"

      - name: Clone and Push to github package repository
        env:
          GITHUB_TOKEN: ${{ secrets.GIT_AUTH_TOKEN }}
          GITHUB_USERNAME: ${{ github.repository_owner }}
        run: |
          node bin clone --bare underpostnet/pwa-microservices-template-ghpkg
          rm -rf ./.git
          mv ./pwa-microservices-template-ghpkg.git ./.git
          pwd
          git remote set-url origin git@github.com:underpostnet/pwa-microservices-template-ghpkg.git
          git init
          git add .
          # Installed modules never enter the package repository; a deletion is the cleanup and passes.
          if git diff --cached --name-only --diff-filter=AM | grep -q '^node_modules/'; then
            echo "::error::node_modules is staged for commit; the template .gitignore must ignore it."
            exit 1
          fi
          git status
          git commit -m "$CHANGE_MESSAGE"
          node bin push . underpostnet/pwa-microservices-template-ghpkg
          node bin github dispatch underpostnet/engine mirror-to-org.yml --ref master --input repos=pwa-microservices-template-ghpkg

  engine-ghpkg:
    if: (github.repository == 'underpostnet/engine' || github.repository == 'underpost/engine') && github.event_name == 'workflow_dispatch'
    name: Build engine ${{ github.event.inputs.conf_id || 'cyberia' }} ghpkg repository
    runs-on: ubuntu-latest
    container:
      image: quay.io/rockylinux/rockylinux:9
    permissions:
      contents: write
      packages: write
      id-token: write
    steps:
      # Install git first. Checkout without git downloads an archive that has no .git.
      - name: Install required packages
        run: |
          dnf install -y sudo tar gzip bzip2 git
          dnf install -y curl --allowerasing

      - name: Clone repository
        uses: actions/checkout@v7

      # The checkout belongs to another user than the container root. Git refuses it without this.
      - name: Trust the checkout in git
        run: git config --global --add safe.directory '*'

      - name: Install Node.js
        run: |
          curl -fsSL https://rpm.nodesource.com/setup_24.x | bash -
          dnf install nodejs -y

      - name: Install dependencies
        run: npm install

      - name: Resolve canonical github package repo
        run: |
          CONF_ID="${{ github.event.inputs.conf_id }}"
          CONF_ID="${CONF_ID:-cyberia}"
          echo "CONF_ID=$CONF_ID" >> $GITHUB_ENV
          echo "GHPKG_REPO=engine-ghpkg-$CONF_ID" >> $GITHUB_ENV
          echo "PACKAGE_NAME=@underpostnet/$CONF_ID" >> $GITHUB_ENV
          echo "[INFO] Canonical github package repo: underpostnet/engine-ghpkg-$CONF_ID"

      - name: Resolve the change summary
        env:
          # Never interpolated into the script: a change summary is free text, which a shell
          # expansion would corrupt or execute.
          CHANGE_SUMMARY: ${{ github.event.inputs.change_summary }}
        run: |
          CHANGE_SUMMARY=$(node bin release --change-summary --fallback "Update canonical github package repo")
          CHANGE_MESSAGE=$(CHANGE_SUMMARY="$CHANGE_SUMMARY" node bin release --change-summary --format message)
          {
            echo "CHANGE_SUMMARY=$CHANGE_SUMMARY"
            echo "CHANGE_MESSAGE<<CHANGE_SUMMARY_EOF"
            echo "$CHANGE_MESSAGE"
            echo "CHANGE_SUMMARY_EOF"
          } >> "$GITHUB_ENV"
          echo "[INFO] Change summary: $CHANGE_SUMMARY"

      - name: Set git global credentials
        env:
          GITHUB_USERNAME: ${{ github.repository_owner }}
          GITHUB_EMAIL: ${{ secrets.GIT_EMAIL }}
        run: |
          : "${GITHUB_EMAIL:?the GIT_EMAIL Actions secret is not set}"
          git config --global credential.helper ""
          git config --global user.name "$GITHUB_USERNAME"
          git config --global user.email "$GITHUB_EMAIL"

      - name: Mirror engine-$CONF_ID and Push to canonical github package repository
        env:
          GITHUB_TOKEN: ${{ secrets.GIT_AUTH_TOKEN }}
          GITHUB_USERNAME: ${{ github.repository_owner }}
        run: |
          cd .. && node engine/bin clone underpostnet/engine-$CONF_ID
          node engine/bin clone --bare underpostnet/$GHPKG_REPO
          cd engine-$CONF_ID
          rm -rf ./.git
          mv ../$GHPKG_REPO.git ./.git
          node ../engine/bin package --rename "$PACKAGE_NAME"
          node ../engine/bin package --set-repo underpostnet/$GHPKG_REPO
          git init
          git add .
          if git diff --cached --quiet; then
            echo "[INFO] No changes to publish; skipping commit and push."
          else
            git commit -m "$CHANGE_MESSAGE"
            node ../engine/bin push . underpostnet/$GHPKG_REPO
            node ../engine/bin github dispatch underpostnet/engine mirror-to-org.yml --ref master --input repos="$GHPKG_REPO"
          fi
