name: Deploy Website

on:
  push:
    branches: [main]

jobs:
  build-and-deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout latest code
        run: |
          if [ -d /tmp/web-projects ]; then
            cd /tmp/web-projects && git pull
          else
            git clone http://localhost:3000/suche-Hermes/web-projects.git /tmp/web-projects
          fi

      - name: Build Astro site
        run: |
          docker run --rm \
            -v /tmp/web-projects:/app \
            -w /app \
            node:22-alpine sh -c "npm install && npm run build"

      - name: Install Nginx config
        run: |
          mkdir -p /etc/nginx/conf.d 2>/dev/null
          cp /tmp/web-projects/nginx/longde.cloud.conf /etc/nginx/conf.d/longde.cloud.conf
          # fallback for sites-enabled style
          mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled 2>/dev/null
          cp /tmp/web-projects/nginx/longde.cloud.conf /etc/nginx/sites-available/longde.cloud.conf 2>/dev/null
          ln -sf /etc/nginx/sites-available/longde.cloud.conf /etc/nginx/sites-enabled/longde.cloud.conf 2>/dev/null

      - name: Deploy to web root
        run: |
          rm -rf /var/www/longde.cloud/*
          cp -r /tmp/web-projects/dist/* /var/www/longde.cloud/

      - name: Reload Nginx
        run: nginx -s reload
