#!/bin/bash

# Strapi CMS Start Script
# Handles both development and production modes

set -e

echo "=========================================="
echo "Strapi CMS Start Script"
echo "=========================================="
echo ""

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# Get script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd "$SCRIPT_DIR"

# Check if .env exists
if [ ! -f ".env" ]; then
    echo -e "${RED}Error: .env file not found!${NC}"
    echo "Please create .env file with required configuration"
    exit 1
fi

# Check mode
MODE=${1:-production}

if [ "$MODE" = "dev" ] || [ "$MODE" = "development" ]; then
    echo -e "${GREEN}Starting Strapi in DEVELOPMENT mode...${NC}"
    echo ""
    npm run develop
elif [ "$MODE" = "pm2" ]; then
    echo -e "${GREEN}Starting Strapi with PM2...${NC}"
    echo ""
    
    # Build first
    if [ ! -d "dist" ]; then
        echo -e "${YELLOW}Building Strapi...${NC}"
        npm run build
    fi
    
    # Stop existing if running
    pm2 stop nrel-cms 2>/dev/null || true
    pm2 delete nrel-cms 2>/dev/null || true
    
    # Start with PM2
    pm2 start ecosystem.config.js
    pm2 save
    
    echo ""
    echo -e "${GREEN}Strapi started with PM2!${NC}"
    echo ""
    echo "Useful commands:"
    echo "  pm2 status              # Check status"
    echo "  pm2 logs nrel-cms       # View logs"
    echo "  pm2 restart nrel-cms   # Restart"
    echo "  pm2 stop nrel-cms       # Stop"
else
    echo -e "${GREEN}Starting Strapi in PRODUCTION mode...${NC}"
    echo ""
    
    # Build first
    if [ ! -d "dist" ]; then
        echo -e "${YELLOW}Building Strapi...${NC}"
        npm run build
    fi
    
    npm run start
fi

