#!/bin/bash

# Fix PM2 ecosystem.config.js path for production server

set -e

echo "=========================================="
echo "Fix PM2 Path for Strapi CMS"
echo "=========================================="
echo ""

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

# Get current directory
CURRENT_DIR=$(pwd)
echo -e "${GREEN}Current directory: $CURRENT_DIR${NC}"
echo ""

# Check if we're in the right directory
if [ ! -f "package.json" ]; then
    echo -e "${RED}Error: package.json not found in current directory${NC}"
    echo -e "${YELLOW}Please navigate to the nrel-cms directory first${NC}"
    echo ""
    echo "Example:"
    echo "  cd /path/to/nrel-cms"
    echo "  bash fix-pm2-path.sh"
    exit 1
fi

# Get absolute path
ABS_PATH=$(cd "$(dirname "$0")" && pwd)
echo -e "${GREEN}Strapi CMS directory: $ABS_PATH${NC}"
echo ""

# Backup ecosystem.config.js
if [ -f "ecosystem.config.js" ]; then
    cp ecosystem.config.js ecosystem.config.js.backup.$(date +%Y%m%d-%H%M%S)
    echo -e "${GREEN}Backed up ecosystem.config.js${NC}"
fi

# Update ecosystem.config.js with correct path
cat > ecosystem.config.js << EOF
module.exports = {
  apps: [
    {
      name: "nrel-cms",
      script: "npm",
      args: "run start",
      cwd: "$ABS_PATH",
      instances: 1,
      exec_mode: "fork",
      env: {
        NODE_ENV: "production",
        PORT: 1337,
        HOST: "0.0.0.0",
        PUBLIC_URL: "https://cms.navana-realestate.com",
      },
      error_file: "$ABS_PATH/logs/pm2-error.log",
      out_file: "$ABS_PATH/logs/pm2-out.log",
      log_date_format: "YYYY-MM-DD HH:mm:ss Z",
      merge_logs: true,
      autorestart: true,
      max_memory_restart: "1G",
      watch: false,
      kill_timeout: 5000,
      wait_ready: true,
      listen_timeout: 10000,
    },
  ],
};
EOF

echo -e "${GREEN}Updated ecosystem.config.js with path: $ABS_PATH${NC}"
echo ""

# Verify the file
echo -e "${YELLOW}Verifying ecosystem.config.js:${NC}"
cat ecosystem.config.js | grep "cwd:"
echo ""

echo -e "${GREEN}✓ Path fixed!${NC}"
echo ""
echo "Next steps:"
echo "  1. Stop existing PM2 process:"
echo "     pm2 stop nrel-cms"
echo "     pm2 delete nrel-cms"
echo ""
echo "  2. Start with updated config:"
echo "     pm2 start ecosystem.config.js"
echo ""
echo "  3. Check status:"
echo "     pm2 status"
echo "     pm2 logs nrel-cms"
echo ""

