#!/bin/bash

echo "[DEPLOY] Starting deployment process..."
echo "[DEPLOY] Deployment started at: $(date)"

cd "$(dirname "$0")"

echo ""
echo "[DEPLOY] Pulling latest changes from Git..."
git pull origin main

if [ $? -ne 0 ]; then
    echo "[ERROR] Git pull failed!"
    exit 1
fi

echo ""
echo "[DEPLOY] Checking for package.json changes..."
PACKAGE_CHANGED=$(git diff HEAD@{1} HEAD --name-only | grep -q "package.json" && echo "yes" || echo "no")

if [ "$PACKAGE_CHANGED" = "yes" ]; then
    echo "[DEPLOY] package.json has changed, running npm install..."
    npm install
    
    if [ $? -ne 0 ]; then
        echo "[ERROR] npm install failed!"
        exit 1
    fi
    
    echo ""
    echo "[DEPLOY] Running npm audit fix..."
    npm audit fix
else
    echo "[DEPLOY] No package.json changes detected, skipping npm install"
fi

echo ""
echo "[DEPLOY] Building CSS with Tailwind..."
npm run build:css

if [ $? -ne 0 ]; then
    echo "[ERROR] CSS build failed!"
    exit 1
fi

echo ""
echo "[DEPLOY] Building obfuscated JavaScript files..."
npm run build

if [ $? -ne 0 ]; then
    echo "[WARN] JS build failed, but continuing deployment..."
fi

echo ""
echo "[DEPLOY] Restarting PM2 process 3..."
pm2 restart 3

if [ $? -ne 0 ]; then
    echo "[ERROR] PM2 restart failed!"
    exit 1
fi

echo ""
echo "[DEPLOY] Deployment completed successfully!"
echo "[DEPLOY] Deployment finished at: $(date)"
