name: Déploiement PROD
run-name: ${{ gitea.actor }} déploie en PROD
on:
  push:
    branches:
      - main

jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'
          extensions: curl, intl, mbstring, xml

      - name: Lint PHP (tous les fichiers, samples inclus)
        run: |
          fail=0
          while IFS= read -r f; do
            php -l "$f" > /dev/null || { echo "::error file=$f::Erreur de syntaxe PHP"; fail=1; }
          done < <(find . -path ./.git -prune -o \( -name '*.php' -o -name '*.php.sample' \) -print)
          [ "$fail" -eq 0 ] && echo "PHP lint OK" || exit 1

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Lint JS (sw.js et js/*.js)
        run: |
          for f in sw.js js/*.js; do
            node --check "$f" || exit 1
          done
          echo "JS lint OK"

      - name: Installer Asciidoctor
        run: sudo gem install asciidoctor

      - name: Valider README.adoc
        run: asciidoctor -o /tmp/readme.html README.adoc

      - name: Valider JSON et XML
        run: |
          sudo apt-get update && sudo apt-get install -y libxml2-utils
          python3 -m json.tool site.webmanifest.sample > /dev/null
          xmllint --noout sitemap.xml.sample browserconfig.xml

      - name: Shellcheck (scripts shell)
        run: |
          sudo apt-get install -y shellcheck
          shellcheck docs/generate-readme-pdf.sh scripts/check.sh

  deploy:
    needs: check
    runs-on: ubuntu-latest
    steps:
      - name: Déployer sur le serveur
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.SSH_HOST }}
          username: ${{ secrets.SSH_USER }}
          key: ${{ secrets.SSH_KEY }}
          script: |
            set -e
            cd ${{ secrets.PROD_DEPLOY_PATH }}

            # Annuler le bump de version du déploiement précédent pour
            # garantir le fast-forward, puis récupérer la dernière version.
            git checkout -- sw.js
            git pull --ff-only origin main

            # Bumper la version des caches du Service Worker : chaque
            # déploiement déclenche le modal de mise à jour PWA chez les
            # visiteurs (voir js/pwa-update.js). Ce bump n'est pas commité.
            VERSION=$(date +%d%m%Y-%H%M)
            sed -i "s/annu-kute-ced-static-[0-9]\{8\}-[0-9]\{4\}/annu-kute-ced-static-$VERSION/" sw.js
            sed -i "s/annu-kute-ced-dynamic-[0-9]\{8\}-[0-9]\{4\}/annu-kute-ced-dynamic-$VERSION/" sw.js
            echo "Version des caches bumpée : $VERSION"
