#!/bin/bash

# Configuration
ZIP_NAME="knowbuildqerp.zip"
REMOTE_HOST="knowbuild"
REMOTE_DIR="/var/www/html/knowbuild-com"
PORT=3100
PM2_NAME="nextjs-app"

echo "🚀 Starting deployment process..."

# 1. Create a zip of current files excluding node_modules, .git, and .next
echo "📦 Zipping files (excluding node_modules, .git, .next)..."
zip -r $ZIP_NAME . -x "node_modules/*" ".git/*" ".next/*" "knowbuildqerp.zip"

# 2. SCP the zip file to the remote server
echo "📤 Uploading $ZIP_NAME to $REMOTE_HOST..."
scp $ZIP_NAME $REMOTE_HOST:$REMOTE_DIR/

# 3. SSH and execute remote commands
echo "🔧 Executing remote commands..."
ssh $REMOTE_HOST << EOF
  cd $REMOTE_DIR
  echo "📂 Unzipping files..."
  unzip -o $ZIP_NAME
  
  echo "📦 Installing dependencies..."
  pnpm i
  
  echo "🏗️ Building project..."
  pnpm build
  
  echo "🔄 Restarting application with PM2..."
  pm2 stop $PM2_NAME || true
  pm2 delete $PM2_NAME || true
  PORT=$PORT pm2 start npm --name "$PM2_NAME" -- start
  
  echo "✅ Remote deployment steps completed!"
EOF

# 4. Cleanup local zip
echo "🧹 Cleaning up local zip file..."
rm $ZIP_NAME

echo "✨ Deployment finished successfully!"
