#!/bin/bash

# Deployment script for Chocolate Ordering System
# Run this on your cPanel server to update from GitHub

echo "========================================="
echo "Deploying Chocolate Ordering System"
echo "========================================="

# Colors for output
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color

# Stop the application (if using pm2)
echo -e "\n${GREEN}Stopping application...${NC}"
pm2 stop chocolate-ordering || echo "Not running with pm2"

# Pull latest changes from GitHub
echo -e "\n${GREEN}Pulling latest changes from GitHub...${NC}"
git pull origin main

if [ $? -ne 0 ]; then
    echo -e "${RED}Git pull failed! Please resolve conflicts manually.${NC}"
    exit 1
fi

# Install/update dependencies
echo -e "\n${GREEN}Installing dependencies...${NC}"
npm install

if [ $? -ne 0 ]; then
    echo -e "${RED}npm install failed!${NC}"
    exit 1
fi

# Create necessary directories if they don't exist
echo -e "\n${GREEN}Creating required directories...${NC}"
mkdir -p uploads
mkdir -p public/images
mkdir -p public/catalogue

# Set permissions
echo -e "\n${GREEN}Setting permissions...${NC}"
chmod 755 uploads
chmod 755 public/images
chmod 755 public/catalogue

# Start the application (if using pm2)
echo -e "\n${GREEN}Starting application...${NC}"
pm2 start server.js --name chocolate-ordering || node server.js &

# Show status
echo -e "\n${GREEN}=========================================${NC}"
echo -e "${GREEN}Deployment complete!${NC}"
echo -e "${GREEN}=========================================${NC}"

# If using pm2, show the status
pm2 status 2>/dev/null || echo ""

echo -e "\nApplication should be running now."
echo -e "Check the logs with: ${GREEN}pm2 logs chocolate-ordering${NC}"
