name: Build and Deploy

on:
  push:
    branches:
      - main

jobs:
  verify:
    runs-on: larablog-ci
    steps:
      - uses: https://gitea.neatcn.com/gouki/action-checkout@v4
      - name: Verify CI runtime
        run: |
          php -r 'exit(PHP_VERSION_ID >= 80200 ? 0 : 1);'
          node --version
          composer --version
      - name: Prepare env (sqlite for package discovery)
        run: |
          cp .env.example .env
          mkdir -p database
          touch database/database.sqlite
      - name: Install backend dependencies
        run: |
          composer install --no-interaction --prefer-dist
          npm install
      - name: Build backend assets
        run: npm run build
      - name: Persist built assets for deploy job
        run: |
          dest="/ci-artifacts/build-${{ gitea.sha }}"
          test -d /ci-artifacts
          rm -rf "$dest"
          mkdir -p "$dest"
          cp -a public/build/. "$dest/"
          test -f "$dest/manifest.json"

  deploy:
    needs: verify
    runs-on: production
    steps:
      - uses: https://gitea.neatcn.com/gouki/action-checkout@v4
      - name: Restore built assets from runner host
        run: |
          src="/opt/larablog/ci-artifacts/build-${{ gitea.sha }}"
          test -d "$src"
          mkdir -p public/build
          cp -a "$src/." public/build/
          test -f public/build/manifest.json
      - uses: https://gitea.neatcn.com/gouki/deployment-toolkit/actions/laravel-release@v1.0.6
        with:
          source-dir: .
          deploy-root: /opt/1panel/apps/openresty/openresty/www/sites/larablog.neatstudio.com/index
          container-deploy-root: /www/sites/larablog.neatstudio.com/index
          php-container: php83-ex
          healthcheck-url: https://larablog.neatstudio.com/up
          backup-command: "mysqldump -h10.0.4.7 -ularablog -p'Larablog#2026' larablog | gzip > /opt/larablog/backups/larablog-${{ gitea.sha }}.sql.gz"
          release-id: ${{ gitea.sha }}
