# Deploy honey-be to VPS on push to main.
# Required secret: DEPLOY_SSH_PRIVATE_KEY.
# Optional: DEPLOY_VPS_HOST (default 188.116.23.7), DEPLOY_VPS_USER (default root).
name: Deploy to VPS
on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      VPS_HOST: ${{ secrets.DEPLOY_VPS_HOST }}
      VPS_USER: ${{ secrets.DEPLOY_VPS_USER }}
    steps:
      # Manual checkout: job container cannot resolve 'server', so clone via host IP (gateway).
      # Set secret GITEA_HOST_IP to your runner host's gateway (from job: ip route show default | awk '{print $3}').
      - name: Checkout
        run: |
          GITEA_HOST="${GITEA_HOST_IP:-172.20.0.1}"
          git clone --depth 1 "http://oauth2:${GITHUB_TOKEN}@${GITEA_HOST}:3000/admin/honey-be.git" .
          git fetch --depth 1 origin "${{ github.sha }}"
          git checkout -q "${{ github.sha }}"
        env:
          GITHUB_TOKEN: ${{ github.token }}
          GITEA_HOST_IP: ${{ secrets.GITEA_HOST_IP }}

      - name: Install SSH and Rsync
        run: |
          apt-get update -qq
          apt-get install -y -qq openssh-client rsync

      - name: Setup SSH
        env:
          SSH_HOST: ${{ secrets.DEPLOY_VPS_HOST }}
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          eval "$(ssh-agent -s)"
          ssh-add ~/.ssh/deploy_key
          HOST="${SSH_HOST:-188.116.23.7}"
          ssh-keyscan -H "$HOST" >> ~/.ssh/known_hosts 2>/dev/null || true

      - name: Sync code to VPS
        run: |
          HOST="${VPS_HOST:-188.116.23.7}"
          USER="${VPS_USER:-root}"
          rsync -avz --delete -e "ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=accept-new" \
            --exclude '.git' \
            --exclude 'target' \
            ./ "$USER@$HOST:/opt/app/backend/honey-be/"

      - name: Run rolling update on VPS
        run: |
          HOST="${VPS_HOST:-188.116.23.7}"
          USER="${VPS_USER:-root}"
          ssh -i ~/.ssh/deploy_key "$USER@$HOST" "cd /opt/app/backend/honey-be && chmod +x scripts/rolling-update.staged.sh && sudo ./scripts/rolling-update.staged.sh"
