#!/bin/bash

# SmartINBOX Installation Script
# Adapted for CloudLinux VPS with cPanel and PHP 8.2

set -e

# Colors for output
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Print section header
section() {
    echo -e "\n${GREEN}==== $1 ====${NC}\n"
}

# Print info message
info() {
    echo -e "${YELLOW}INFO: $1${NC}"
}

# Print success message
success() {
    echo -e "${GREEN}SUCCESS: $1${NC}"
}

# Print error message
error() {
    echo -e "${RED}ERROR: $1${NC}"
}

# Check if command exists
command_exists() {
    command -v "$1" >/dev/null 2>&1
}

# Configuration for your setup
DOMAIN="smartersweb.host"
SUBDOMAIN="smartinbox"
INSTALL_DIR="/home/smartersweb/public_html/smartinbox"
SOURCE_DIR="$(pwd)"
WEB_USER="smartersweb"
WEB_GROUP="smartersweb"
CLEAN_INSTALL=false

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    key="$1"
    case $key in
        --clean)
            CLEAN_INSTALL=true
            shift
            ;;
        --domain=*)
            DOMAIN="${key#*=}"
            shift
            ;;
        --subdomain=*)
            SUBDOMAIN="${key#*=}"
            shift
            ;;
        --install-dir=*)
            INSTALL_DIR="${key#*=}"
            shift
            ;;
        --web-user=*)
            WEB_USER="${key#*=}"
            shift
            ;;
        --web-group=*)
            WEB_GROUP="${key#*=}"
            shift
            ;;
        --help)
            echo "Usage: $0 [options]"
            echo "Options:"
            echo "  --clean                Clean installation (removes existing files)"
            echo "  --domain=DOMAIN        Domain name (default: smartersweb.host)"
            echo "  --subdomain=SUBDOMAIN  Subdomain name (default: smartinbox)"
            echo "  --install-dir=DIR      Installation directory (default: /home/smartersweb/public_html/smartinbox)"
            echo "  --web-user=USER        Web server user (default: smartersweb)"
            echo "  --web-group=GROUP      Web server group (default: smartersweb)"
            echo "  --help                 Show this help message"
            exit 0
            ;;
        *)
            error "Unknown option: $key"
            exit 1
            ;;
    esac
done

section "SmartINBOX Installation"
info "This script will install SmartINBOX on your CloudLinux VPS"
info "Target URL: https://www.${DOMAIN}/${SUBDOMAIN}/"
if [ "$CLEAN_INSTALL" = true ]; then
    info "Clean installation: Existing files will be removed"
fi

# Check if running as root
if [ "$EUID" -ne 0 ]; then
    error "Please run this script as root or with sudo"
    exit 1
fi

section "Checking Prerequisites"

# Check PHP version
if command_exists php; then
    PHP_VERSION=$(php -v | head -n 1 | cut -d " " -f 2 | cut -d "." -f 1,2)
    if [ "$PHP_VERSION" != "8.2" ]; then
        error "PHP 8.2 is required, found $PHP_VERSION"
        exit 1
    else
        info "PHP $PHP_VERSION detected"
    fi
else
    error "PHP not found"
    exit 1
fi

# Check Node.js
if command_exists node; then
    NODE_VERSION=$(node -v | cut -d "v" -f 2 | cut -d "." -f 1)
    if [ "$NODE_VERSION" -lt 20 ]; then
        error "Node.js 20.x or higher is required, found v$NODE_VERSION"
        exit 1
    else
        info "Node.js $(node -v) detected"
    fi
else
    error "Node.js not found"
    exit 1
fi

# Check NPM
if command_exists npm; then
    info "NPM $(npm -v) detected"
else
    error "NPM not found"
    exit 1
fi

# Check MariaDB
if command_exists mysql; then
    info "MariaDB detected"
else
    error "MariaDB not found"
    exit 1
fi

# Check Redis
if command_exists redis-cli; then
    info "Redis detected"
else
    info "Installing Redis..."
    yum install -y redis
    systemctl enable redis
    systemctl start redis
fi

section "Creating Installation Directory"

# Check if installation directory exists
if [ -d "$INSTALL_DIR" ]; then
    if [ "$CLEAN_INSTALL" = true ]; then
        info "Removing existing installation directory..."
        # Stop any running services
        if [ -f "$INSTALL_DIR/stop.sh" ]; then
            info "Stopping existing SmartINBOX service..."
            cd "$INSTALL_DIR" && ./stop.sh || true
        fi
        
        # Check if systemd service exists and stop it
        if systemctl is-active --quiet smartinbox.service; then
            info "Stopping systemd service..."
            systemctl stop smartinbox.service || true
        fi
        
        # Remove node_modules directory first (can cause issues with rm -rf)
        if [ -d "$INSTALL_DIR/node_modules" ]; then
            info "Removing node_modules directory..."
            rm -rf "$INSTALL_DIR/node_modules"
        fi
        
        # Remove the entire directory
        info "Removing existing files..."
        rm -rf "$INSTALL_DIR"
        mkdir -p "$INSTALL_DIR"
    else
        info "Installation directory already exists"
        info "Backing up existing configuration..."
        
        # Backup existing .env file if it exists
        if [ -f "$INSTALL_DIR/.env" ]; then
            cp "$INSTALL_DIR/.env" "$INSTALL_DIR/.env.backup.$(date +%Y%m%d%H%M%S)"
            info "Backed up .env file"
        fi
        
        # Backup existing database configuration if it exists
        if [ -d "$INSTALL_DIR/config" ]; then
            mkdir -p "$INSTALL_DIR/config.backup.$(date +%Y%m%d%H%M%S)"
            cp -r "$INSTALL_DIR/config/"* "$INSTALL_DIR/config.backup.$(date +%Y%m%d%H%M%S)/"
            info "Backed up configuration files"
        fi
    fi
else
    mkdir -p "$INSTALL_DIR"
fi

chown -R $WEB_USER:$WEB_GROUP "$INSTALL_DIR"

section "Copying Source Files"
# Copy all files from the current directory to the installation directory
# Skip node_modules directory if it exists
info "Copying files to installation directory..."
rsync -av --exclude='node_modules' "$SOURCE_DIR/"* "$INSTALL_DIR/"
rsync -av --exclude='node_modules' "$SOURCE_DIR/".env* "$INSTALL_DIR/" 2>/dev/null || true

# Make sure scripts are executable
chmod +x "$INSTALL_DIR/"*.sh 2>/dev/null || true

# Set proper ownership
chown -R $WEB_USER:$WEB_GROUP "$INSTALL_DIR"

section "Creating Directory Structure"
# Create necessary directories if they don't exist
mkdir -p "$INSTALL_DIR/public"
mkdir -p "$INSTALL_DIR/public/css"
mkdir -p "$INSTALL_DIR/public/js"
mkdir -p "$INSTALL_DIR/public/images"
mkdir -p "$INSTALL_DIR/data"
mkdir -p "$INSTALL_DIR/logs"
mkdir -p "$INSTALL_DIR/config"

# Set proper ownership
chown -R $WEB_USER:$WEB_GROUP "$INSTALL_DIR"

section "Installing Dependencies"
cd "$INSTALL_DIR"

# Check if node_modules directory exists and is not empty
if [ -d "$INSTALL_DIR/node_modules" ] && [ "$(ls -A "$INSTALL_DIR/node_modules")" ]; then
    if [ "$CLEAN_INSTALL" = true ]; then
        info "Removing existing node_modules directory..."
        rm -rf "$INSTALL_DIR/node_modules"
        sudo -u $WEB_USER npm install
    else
        info "Node modules already installed, skipping npm install"
        info "If you encounter issues, run with --clean option or manually run: npm install"
    fi
else
    sudo -u $WEB_USER npm install
fi

section "Creating .htaccess File"
cat > "$INSTALL_DIR/.htaccess" << 'EOF'
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /smartinbox/
    
    # If the request is for an existing file or directory, serve it directly
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    
    # For API requests, proxy to Node.js
    RewriteCond %{REQUEST_URI} ^/smartinbox/api/
    RewriteRule ^api/(.*)$ http://localhost:3000/api/$1 [P,L]
    
    # For all other requests, serve the index.html file
    RewriteRule ^ index.html [L]
</IfModule>

# Set security headers
<IfModule mod_headers.c>
    Header set X-Content-Type-Options "nosniff"
    Header set X-XSS-Protection "1; mode=block"
    Header set X-Frame-Options "SAMEORIGIN"
    Header set Referrer-Policy "strict-origin-when-cross-origin"
</IfModule>
EOF

# Set proper ownership
chown $WEB_USER:$WEB_GROUP "$INSTALL_DIR/.htaccess"

section "Creating Service Files"
# Create a systemd service file for the Node.js application
cat > /etc/systemd/system/smartinbox.service << EOF
[Unit]
Description=SmartINBOX Node.js Application
After=network.target

[Service]
Type=simple
User=$WEB_USER
WorkingDirectory=$INSTALL_DIR
ExecStart=/usr/bin/node $INSTALL_DIR/server.js
Restart=on-failure
Environment=PORT=3000
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
EOF

# Reload systemd
systemctl daemon-reload

# Enable and start the service
systemctl enable smartinbox.service
systemctl start smartinbox.service

section "Creating PM2 Configuration (Alternative)"
# Create a PM2 configuration file for those who prefer PM2
cat > "$INSTALL_DIR/ecosystem.config.js" << EOF
module.exports = {
  apps: [{
    name: "smartinbox",
    script: "server.js",
    env: {
      NODE_ENV: "production",
      PORT: 3000
    },
    watch: false,
    instances: 1,
    autorestart: true,
    max_memory_restart: "200M"
  }]
};
EOF

# Set proper ownership
chown $WEB_USER:$WEB_GROUP "$INSTALL_DIR/ecosystem.config.js"

info "To use PM2 instead of systemd, run: pm2 start ecosystem.config.js"

section "Installation Complete"
info "SmartINBOX has been installed successfully!"
info "Installation directory: $INSTALL_DIR"
info "Target URL: https://www.$DOMAIN/$SUBDOMAIN/"
info ""
info "Next steps:"
info "1. Make sure your domain/subdomain in cPanel points to $INSTALL_DIR"
info "2. Check that the Node.js service is running: systemctl status smartinbox.service"
info "3. Test the installation by visiting your URL"
info "4. If you encounter any issues, check the logs in $INSTALL_DIR/logs/"

# Check if the service is running
if systemctl is-active --quiet smartinbox.service; then
    success "SmartINBOX service is running"
else
    error "SmartINBOX service is not running. Check logs with: journalctl -u smartinbox.service"
fi

echo ""
success "Installation completed successfully!"