name: Check and deploy

on:
  push:
    branches:
      - main
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    timeout-minutes: 10

    steps:
      - name: Check out the site
        uses: actions/checkout@v4

      - name: Set up Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Validate the site
        run: npm run check

      - name: Assemble the static site
        run: |
          install -d dist
          cp index.html styles.css dist/
          cp -R src vendor tiles dist/

      - name: Install deployment tools
        run: |
          apt-get update
          apt-get install --yes --no-install-recommends openssh-client rsync

      - name: Configure deployment SSH key
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
          DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
        run: |
          install -d -m 0700 "$HOME/.ssh"
          printf '%s\n' "$DEPLOY_SSH_KEY" > "$HOME/.ssh/deploy_key"
          printf '%s\n' "$DEPLOY_KNOWN_HOSTS" > "$HOME/.ssh/known_hosts"
          chmod 0600 "$HOME/.ssh/deploy_key" "$HOME/.ssh/known_hosts"

      - name: Upload the website
        env:
          DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
        run: |
          rsync \
            --archive \
            --compress \
            --delete \
            --delay-updates \
            --human-readable \
            --itemize-changes \
            --rsh "ssh -i $HOME/.ssh/deploy_key -o IdentitiesOnly=yes" \
            dist/ \
            "a-plot-of-plants-deploy@${DEPLOY_HOST}:/var/www/html/a-plot-of-plants/"
