#!/bin/bash

set -e

APP_DIR="/var/www/html/api"

echo "===================================="
echo "Starting Node.js deployment..."
echo "===================================="

cd "$APP_DIR"  # quote to handle spaces

echo "Current directory:"
pwd

echo "Node version:"
node -v

echo "NPM version:"
npm -v

echo "Installing dependencies..."
npm install

# echo "Building application..."
# npm run build

echo "Restarting PM2 process..."
# Check if the process exists before restarting
if pm2 list | grep -q "Green-Rubies-7702"; then
    pm2 restart Green-Rubies-7702
else
    echo "PM2 process Green-Rubies-7702 not found. Starting it..."
    pm2 start npm --name Green-Rubies-7702 -- start
fi

echo "Deployment completed successfully!"
echo "===================================="