name: Build and deploy

on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: npm

      - name: Install dependencies
        run: npm ci

      - name: Type and link check
        run: npm run check

      - name: Build
        run: npm run build

      - name: Install lftp
        run: |
          sudo apt-get update -qq
          sudo apt-get install -y --no-install-recommends lftp

      - name: SFTP mirror via lftp
        env:
          SFTP_HOST: ${{ secrets.SFTP_HOST }}
          SFTP_PORT: ${{ secrets.SFTP_PORT }}
          SFTP_USER: ${{ secrets.SFTP_USER }}
          SFTP_PASS: ${{ secrets.SFTP_PASS }}
          SFTP_PATH: ${{ secrets.SFTP_PATH }}
        run: |
          lftp -e "
            set sftp:auto-confirm yes;
            set ssl:verify-certificate no;
            open -u '$SFTP_USER,$SFTP_PASS' sftp://$SFTP_HOST:$SFTP_PORT;
            mirror --reverse --delete --parallel=4 --verbose \
                   --exclude-glob '.well-known/' \
                   ./dist/ $SFTP_PATH;
            bye
          "

      - name: Summary
        if: always()
        run: |
          {
            echo "### Deployed"
            echo ""
            echo "- Commit: ${{ github.sha }}"
            echo "- Page count: $(find dist -name '*.html' 2>/dev/null | wc -l)"
            echo "- Build size: $(du -sh dist 2>/dev/null | cut -f1)"
          } >> "$GITHUB_STEP_SUMMARY"
