#!/bin/bash

# Sites Setup Script for WHP
# This script sets up the sites database schema and integrates it with the existing system

set -e

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# Function to get MySQL credentials
get_mysql_credentials() {
    if [ -f "/root/.my.cnf" ]; then
        # Parse MySQL credentials from config file
        MYSQL_USER=$(grep "^user=" /root/.my.cnf | cut -d'=' -f2)
        MYSQL_PASSWORD=$(grep "^password=" /root/.my.cnf | cut -d'=' -f2)
        MYSQL_HOST=$(grep "^host=" /root/.my.cnf | cut -d'=' -f2)
        MYSQL_PORT=$(grep "^port=" /root/.my.cnf | cut -d'=' -f2)
        
        # Set defaults if not found
        MYSQL_USER=${MYSQL_USER:-root}
        MYSQL_HOST=${MYSQL_HOST:-localhost}
        MYSQL_PORT=${MYSQL_PORT:-3306}
    else
        print_error "MySQL configuration file not found at /root/.my.cnf"
        exit 1
    fi
}

# Function to test MySQL connection
test_mysql_connection() {
    print_status "Testing MySQL connection..."
    
    if mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -h"$MYSQL_HOST" -P"$MYSQL_PORT" -e "SELECT 1;" >/dev/null 2>&1; then
        print_success "MySQL connection successful"
    else
        print_error "Failed to connect to MySQL"
        exit 1
    fi
}

# Function to check if WHP database exists
check_whp_database() {
    print_status "Checking WHP database..."
    
    if mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -h"$MYSQL_HOST" -P"$MYSQL_PORT" -e "USE whp;" >/dev/null 2>&1; then
        print_success "WHP database exists"
    else
        print_error "WHP database does not exist. Please run the main setup script first."
        exit 1
    fi
}

# Function to import sites schema
import_sites_schema() {
    print_status "Importing sites database schema..."
    
    local schema_file="/root/whp/sql/sites-schema.sql"
    
    if [ ! -f "$schema_file" ]; then
        print_error "Sites schema file not found: $schema_file"
        exit 1
    fi
    
    if mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -h"$MYSQL_HOST" -P"$MYSQL_PORT" < "$schema_file"; then
        print_success "Sites schema imported successfully"
    else
        print_error "Failed to import sites schema"
        exit 1
    fi
}

# Function to verify sites tables
verify_sites_tables() {
    print_status "Verifying sites tables..."
    
    local tables=("sites" "site_domains" "site_containers")
    local missing_tables=()
    
    for table in "${tables[@]}"; do
        if mysql -u"$MYSQL_USER" -p"$MYSQL_PASSWORD" -h"$MYSQL_HOST" -P"$MYSQL_PORT" -e "DESCRIBE whp.$table;" >/dev/null 2>&1; then
            print_success "Table 'whp.$table' exists"
        else
            missing_tables+=("$table")
        fi
    done
    
    if [ ${#missing_tables[@]} -eq 0 ]; then
        print_success "All sites tables verified"
    else
        print_error "Missing tables: ${missing_tables[*]}"
        exit 1
    fi
}

# Function to copy web files
copy_web_files() {
    print_status "Copying sites web files..."
    
    local source_dir="/root/whp/web-files"
    local target_dir="/docker/whp/web"
    
    if [ ! -d "$source_dir" ]; then
        print_error "Source directory not found: $source_dir"
        exit 1
    fi
    
    # Copy sites page
    if [ -f "$source_dir/pages/sites.php" ]; then
        cp "$source_dir/pages/sites.php" "$target_dir/pages/"
        print_success "Sites page copied"
    else
        print_error "Sites page not found: $source_dir/pages/sites.php"
        exit 1
    fi
    
    # Copy sites API
    if [ -f "$source_dir/api/sites.php" ]; then
        cp "$source_dir/api/sites.php" "$target_dir/api/"
        print_success "Sites API copied"
    else
        print_error "Sites API not found: $source_dir/api/sites.php"
        exit 1
    fi
    
    # Copy updated index.php
    if [ -f "$source_dir/index.php" ]; then
        cp "$source_dir/index.php" "$target_dir/"
        print_success "Updated index.php copied"
    else
        print_error "Updated index.php not found: $source_dir/index.php"
        exit 1
    fi
    
    # Copy updated domains page
    if [ -f "$source_dir/pages/domains.php" ]; then
        cp "$source_dir/pages/domains.php" "$target_dir/pages/"
        print_success "Updated domains page copied"
    else
        print_error "Updated domains page not found: $source_dir/pages/domains.php"
        exit 1
    fi
    
    # Copy updated permission manager
    if [ -f "$source_dir/libs/permission_manager.php" ]; then
        cp "$source_dir/libs/permission_manager.php" "$target_dir/libs/"
        print_success "Updated permission manager copied"
    else
        print_error "Updated permission manager not found: $source_dir/libs/permission_manager.php"
        exit 1
    fi
}

# Function to restart services
restart_services() {
    print_status "Restarting Apache service..."
    
    if systemctl restart httpd; then
        print_success "Apache service restarted"
    else
        print_warning "Failed to restart Apache service"
    fi
}

# Function to set permissions
set_permissions() {
    print_status "Setting file permissions..."
    
    local web_dir="/docker/whp/web"
    
    # Set proper permissions for web files
    chmod 644 "$web_dir/pages/sites.php"
    chmod 644 "$web_dir/api/sites.php"
    chmod 644 "$web_dir/index.php"
    chmod 644 "$web_dir/pages/domains.php"
    chmod 644 "$web_dir/libs/permission_manager.php"
    
    print_success "File permissions set"
}

# Function to create user directories
create_user_directories() {
    print_status "Creating user directories structure..."
    
    local users_dir="/docker/users"
    
    if [ ! -d "$users_dir" ]; then
        mkdir -p "$users_dir"
        print_success "Created users directory: $users_dir"
    fi
    
    # Set proper permissions
    chmod 755 "$users_dir"
    
    print_success "User directories structure ready"
}

# Function to display completion message
display_completion() {
    echo
    print_success "Sites setup completed successfully!"
    echo
    echo -e "${GREEN}What's been set up:${NC}"
    echo "  ✓ Sites database schema (sites, site_domains, site_containers tables)"
    echo "  ✓ Sites web interface (/sites page)"
    echo "  ✓ Sites API endpoints"
    echo "  ✓ Updated navigation menu"
    echo "  ✓ User directory structure"
    echo
    echo -e "${BLUE}Next steps:${NC}"
    echo "  1. Access the Sites page in your WHP control panel"
    echo "  2. Create your first site by selecting a domain and container type"
    echo "  3. Configure container resources and settings"
    echo "  4. Create and manage containers for your sites"
    echo
    echo -e "${YELLOW}Note:${NC} Domains created in the Domains page will still have a default container type assigned,"
    echo "      but you can now configure them properly in the Sites page."
    echo
}

# Main execution
main() {
    echo -e "${BLUE}================================${NC}"
    echo -e "${BLUE}    WHP Sites Setup Script     ${NC}"
    echo -e "${BLUE}================================${NC}"
    echo
    
    # Check if running as root
    if [ "$EUID" -ne 0 ]; then
        print_error "This script must be run as root"
        exit 1
    fi
    
    # Get MySQL credentials
    get_mysql_credentials
    
    # Test MySQL connection
    test_mysql_connection
    
    # Check WHP database
    check_whp_database
    
    # Import sites schema
    import_sites_schema
    
    # Verify sites tables
    verify_sites_tables
    
    # Copy web files
    copy_web_files
    
    # Set permissions
    set_permissions
    
    # Create user directories
    create_user_directories
    
    # Restart services
    restart_services
    
    # Display completion message
    display_completion
}

# Run main function
main "$@" 