name: Deploy cdrdpyj

on:
  push:
    branches: [staging, production]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set target dir & PM2 env
        run: |
          if [ "${{ gitea.ref_name }}" = "production" ]; then
            echo "TARGET_DIR=/var/www/node/cdrdpyj" >> $GITHUB_ENV
            echo "APP_NAME=cdrdpyj-live" >> $GITHUB_ENV
          else
            echo "TARGET_DIR=/var/www/node/dev.cdrdjyp" >> $GITHUB_ENV
            echo "APP_NAME=cdrdpyj" >> $GITHUB_ENV
          fi

      - uses: pnpm/action-setup@v4
        with:
          version: 11

      - uses: actions/setup-node@v4
        with:
          node-version: '22'

      - run: pnpm install --frozen-lockfile
      - run: pnpm run build

      - name: Copy build to VPS
        uses: appleboy/scp-action@master
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          source: "dist/*,package.json,pnpm-lock.yaml,pnpm-workspace.yaml,ecosystem.config.cjs"
          target: "${{ env.TARGET_DIR }}"

      - name: Restart PM2
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            set -e
            export NVM_DIR="$HOME/.nvm"
            [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"
            npm install -g pnpm@11 2>&1
            cd ${{ env.TARGET_DIR }}
            pnpm install --prod 2>&1
            sed -i "s|TURNSTILE_SITE_KEY: \"\"|TURNSTILE_SITE_KEY: \"${{ secrets.TURNSTILE_SITE_KEY }}\"|g" ecosystem.config.cjs
            sed -i "s|TURNSTILE_SECRET_KEY: \"\"|TURNSTILE_SECRET_KEY: \"${{ secrets.TURNSTILE_SECRET_KEY }}\"|g" ecosystem.config.cjs
            sed -i "s|CLOUDFLARE_API_TOKEN: \"\"|CLOUDFLARE_API_TOKEN: \"${{ secrets.CLOUDFLARE_API_TOKEN }}\"|g" ecosystem.config.cjs
            sed -i "s|CLOUDFLARE_ACCOUNT_ID: \"\"|CLOUDFLARE_ACCOUNT_ID: \"${{ secrets.CLOUDFLARE_ACCOUNT_ID }}\"|g" ecosystem.config.cjs
            pm2 reload ecosystem.config.cjs --only ${{ env.APP_NAME }} --update-env || \
              pm2 start ecosystem.config.cjs --only ${{ env.APP_NAME }} --update-env
