name: Build and deploy updated apps

on:
  push:
    branches: [ main ]
  pull_request:

jobs:
  build:
    name: Build & deploy
    runs-on: ubuntu-latest

    steps:
      - name: Configure ssh
        run: |
          mkdir -p ~/.ssh
          cat << 'EOF' > ~/.ssh/config
          Host *
            StrictHostKeyChecking no
            UserKnownHostsFile=/dev/null
          EOF
          chmod 600 ~/.ssh/config

      - name: Checkout
        uses: https://github.com/actions/checkout@v4
        with:
          fetch-depth: 0 # whole history and tags, can refine this later
          ssh-key: ${{ secrets.GIT_SSH_KEY }}
          ssh-strict: false
          persist-credentials: true

      - name: Setup node
        uses: https://github.com/actions/setup-node@v4
        with:
          node-version: 22

      - name: Setup pnpm
        uses: https://github.com/pnpm/action-setup@v3
        with:
          version: 9
          run_install: false
          cache: true

      - name: Install
        run: pnpm install --frozen-lockfile

      - name: Build affected apps
        run: |
          pnpm turbo run generate \
            --filter="{./apps/*}...[deployed...HEAD]" \
            --concurrency=1

      - name: Gather output
        run: |
         mkdir -p deploy
         
         # could also configure turbo.json to output everything in root-subdir?
         for public in apps/*/.output/public; do
           if [ -d "$public" ]; then
             # Derive the app name (e.g. "marketing" for apps/marketing)
             app=$(basename "$(dirname "$(dirname "$public")")")
             echo "→ Collecting $app"
         
             # Copy its public output into deploy/<app>/
             mkdir -p "deploy/$app"
             cp -r "$public/." "deploy/$app/"
           fi
         done
         
         echo "All sites collected under deploy/:"
         ls -R deploy

      - name: Start ssh agent
        uses: webfactory/ssh-agent@v0.9.0
        with:
          ssh-private-key: |
            ${{ secrets.HOST_SSH_KEY }}
            ${{ secrets.GIT_SSH_KEY }}

      - name: Rsync to web server
        env:
          HOST: ${{ secrets.HOST_NAME }}
          USER: ${{ secrets.HOST_USER }}
        run: |
          apt-get update
          apt-get install -y rsync
          for pub in deploy/*; do
            site=$(basename "$pub" .public)
            echo "Deploying $site to $USER@$HOST:/www/$site"
            ssh -o StrictHostKeyChecking=no "$USER@$HOST" "mkdir -p /srv/www/$site"
            rsync -az --delete "$pub/" "$USER@$HOST:/srv/www/$site/"
          done

      - name: Update deployment tag
        run: | # todo this could cause a race condition
          git config user.name  "CI Bot"
          git config user.email "ci@dominikmilacher.com"
          git tag -f deployed HEAD
          git push origin deployed --force