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

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      VPS_HOST: ${{ secrets.DEPLOY_VPS_HOST }}
      VPS_USER: ${{ secrets.DEPLOY_VPS_USER }}
    steps:
      - name: Checkout
        run: |
          GITEA_HOST="${GITEA_HOST_IP:-172.20.0.1}"
          git clone --depth 1 "http://oauth2:${GITHUB_TOKEN}@${GITEA_HOST}:3000/${{ github.repository }}.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 client
        run: |
          apt-get update -qq
          apt-get install -y -qq openssh-client

      - 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: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10.30.3
          run_install: false

      - name: Configure pnpm store
        run: pnpm config set store-dir /root/.pnpm-store

      - name: Setup Node.js
        uses: actions/setup-node@v6
        with:
          node-version-file: ".nvmrc"

      - name: Cache pnpm store
        uses: actions/cache@v4
        with:
          path: /root/.pnpm-store
          key: pnpm-${{ hashFiles('pnpm-lock.yaml') }}
          restore-keys: pnpm-

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

      - name: Build
        run: pnpm run build:staging

      - name: Deploy dist to VPS dist
        run: |
          HOST="${VPS_HOST:-188.116.23.7}"
          USER="${VPS_USER:-root}"
          REMOTE_DIR="/opt/app/frontend/dist"
          ssh -i ~/.ssh/deploy_key -o StrictHostKeyChecking=accept-new "$USER@$HOST" "mkdir -p $REMOTE_DIR"
          scp -i ~/.ssh/deploy_key -o StrictHostKeyChecking=accept-new -r dist/* "$USER@$HOST:$REMOTE_DIR/"
          echo "Deployed to $USER@$HOST:$REMOTE_DIR/"
