name: Deploy Buku Online → helmibahara.my.id/book/sim/

on:
  push:
    branches: [main]
    paths:
      - "chapters/**"
      - "backmatter/**"
      - "foundation/RPS-SIM.md"
      - "mkdocs.yml"
      - "scripts/sync-docs.py"
  workflow_dispatch:

jobs:
  deploy:
    name: Build MkDocs & Deploy ke vm-edge
    runs-on: ubuntu-latest          # Forgejo self-hosted runner

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

      - name: Setup Python 3.12
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"
          cache: "pip"

      - name: Install MkDocs + Material
        run: |
          pip install --upgrade pip
          pip install \
            mkdocs==1.6.* \
            mkdocs-material==9.* \
            mkdocs-minify-plugin \
            pymdown-extensions

      - name: Sync chapters → docs/
        run: python scripts/sync-docs.py --verbose

      - name: Build site MkDocs
        run: mkdocs build --strict

      # ── Deploy ke vm-edge via rsync over SSH ────────────────────────
      # Secret yang dibutuhkan di Forgejo repo → Settings → Secrets:
      #   DEPLOY_KEY  →  private key (ed25519) untuk akses vm-edge
      # Di vm-edge tambahkan public key ke authorized_keys deploy user
      # ─────────────────────────────────────────────────────────────────
      - name: Setup SSH deploy key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H 192.168.18.202 >> ~/.ssh/known_hosts

      - name: Rsync site/ → vm-edge:/var/www/sim-book/
        run: |
          rsync -avz --delete \
            -e "ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=no" \
            site/ \
            deploy@192.168.18.202:/var/www/sim-book/

      - name: Cleanup SSH key
        if: always()
        run: rm -f ~/.ssh/deploy_key
