name: Deploy to VPS

on:
  push:
    branches:
      - master
  workflow_dispatch:

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout Repository
        uses: actions/checkout@v4
        with:
          submodules: recursive

      - name: Deploy to VPS
        env:
          VPS_HOST: ${{ secrets.VPS_HOST }}
          VPS_USERNAME: ${{ secrets.VPS_USERNAME }}
          VPS_SSH_KEY: ${{ secrets.VPS_SSH_KEY }}
          ENV_FILE: ${{ secrets.ENV_FILE }}
        run: |
          # 1. Setup SSH Key
          mkdir -p ~/.ssh
          echo "$VPS_SSH_KEY" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "$VPS_HOST" >> ~/.ssh/known_hosts
          
          # 2. Ensure target directory exists on VPS
          ssh -i ~/.ssh/id_ed25519 -o StrictHostKeyChecking=no "$VPS_USERNAME@$VPS_HOST" "mkdir -p /opt/imphenbot"
          
          # 3. Rsync codebase (differential transfer)
          rsync -e "ssh -i ~/.ssh/id_ed25519 -o StrictHostKeyChecking=no" -avz \
            --exclude='node_modules' \
            --exclude='.git' \
            --exclude='.github' \
            --exclude='recordings' \
            --exclude='dist' \
            --exclude='.env' \
            --exclude='*.db' \
            --exclude='*.db-shm' \
            --exclude='*.db-wal' \
            --exclude='test_out.nut' \
            ./ "$VPS_USERNAME@$VPS_HOST:/opt/imphenbot/"
            
          # 4. Inject Environment Variables and Build/Restart Containers
          ssh -i ~/.ssh/id_ed25519 -o StrictHostKeyChecking=no "$VPS_USERNAME@$VPS_HOST" "
            cd /opt/imphenbot || exit
            echo \"$ENV_FILE\" > .env
            # Build and restart containers using available docker compose command
            if command -v docker-compose &> /dev/null; then
              docker-compose up -d --build
            else
              docker compose up -d --build
            fi
          "
