#!/bin/bash

#################################################################################
#                         Enjyn Skript Service                                  #
#                       LAMP Stack Install Script                               #
#                     Compatible with Debian 8-12                               #
#                    Compatible with Ubuntu 20.04-24.04                         #
#################################################################################

# Color definitions
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Variables
MYSQL_ROOT_PASS=""
OS_VERSION=""
OS_NAME=""
PHP_VERSION=""
LOG_FILE="/var/log/enjyn_lamp_install.log"

# Functions
print_banner() {
    clear
    echo -e "${PURPLE}"
    echo "╔═══════════════════════════════════════════════════════════════════╗"
    echo "║                      Enjyn Skript Service                         ║"
    echo "║                   LAMP Stack Installation                         ║"
    echo "║                      Version 1.0.0                                ║"
    echo "╚═══════════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_success() {
    echo -e "${GREEN}[✓] $1${NC}"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] SUCCESS: $1" >> "$LOG_FILE"
}

print_error() {
    echo -e "${RED}[✗] $1${NC}"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] ERROR: $1" >> "$LOG_FILE"
}

print_warning() {
    echo -e "${YELLOW}[!] $1${NC}"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] WARNING: $1" >> "$LOG_FILE"
}

print_info() {
    echo -e "${CYAN}[i] $1${NC}"
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] INFO: $1" >> "$LOG_FILE"
}

check_root() {
    if [[ $EUID -ne 0 ]]; then
        print_error "This script must be run as root!"
        exit 1
    fi
}

detect_os() {
    if [[ -f /etc/os-release ]]; then
        . /etc/os-release
        OS_NAME=$ID
        OS_VERSION=$VERSION_ID
    else
        print_error "Cannot detect OS version!"
        exit 1
    fi
    
    case $OS_NAME in
        debian)
            case $OS_VERSION in
                8|9|10|11|12)
                    print_success "Detected: Debian $OS_VERSION"
                    ;;
                *)
                    print_error "Unsupported Debian version: $OS_VERSION"
                    exit 1
                    ;;
            esac
            ;;
        ubuntu)
            case $OS_VERSION in
                20.04|22.04|24.04)
                    print_success "Detected: Ubuntu $OS_VERSION"
                    ;;
                *)
                    print_error "Unsupported Ubuntu version: $OS_VERSION"
                    exit 1
                    ;;
            esac
            ;;
        *)
            print_error "Unsupported OS: $OS_NAME"
            exit 1
            ;;
    esac
}

update_system() {
    print_info "Updating system packages..."
    
    # Update package list
    if apt-get update -y >> "$LOG_FILE" 2>&1; then
        print_success "Package list updated successfully"
    else
        print_error "Failed to update package list"
        exit 1
    fi
    
    # Install software-properties-common for add-apt-repository
    if apt-get install -y software-properties-common >> "$LOG_FILE" 2>&1; then
        print_success "Basic tools installed successfully"
    else
        print_error "Failed to install basic tools"
        exit 1
    fi
}

install_apache() {
    print_info "Installing Apache Web Server..."
    
    # Install Apache
    if apt-get install -y apache2 apache2-utils >> "$LOG_FILE" 2>&1; then
        # Enable and start Apache
        systemctl enable apache2 >> "$LOG_FILE" 2>&1
        systemctl start apache2 >> "$LOG_FILE" 2>&1
        
        # Check if Apache is running
        if systemctl is-active --quiet apache2; then
            print_success "Apache installed and started successfully"
        else
            print_error "Apache installed but failed to start"
            exit 1
        fi
    else
        print_error "Failed to install Apache"
        exit 1
    fi
}

install_mysql() {
    print_info "Installing MySQL Server..."
    
    # Generate secure password
    MYSQL_ROOT_PASS=$(openssl rand -base64 16)
    
    # Check which MySQL package to install based on OS
    if [[ "$OS_NAME" == "debian" && "$OS_VERSION" == "12" ]] || [[ "$OS_NAME" == "ubuntu" && "$OS_VERSION" == "24.04" ]]; then
        MYSQL_PACKAGE="mariadb-server mariadb-client"
        MYSQL_SERVICE="mariadb"
    else
        MYSQL_PACKAGE="mysql-server mysql-client"
        MYSQL_SERVICE="mysql"
    fi
    
    # Pre-configure MySQL/MariaDB to avoid prompts
    export DEBIAN_FRONTEND=noninteractive
    
    # Install MySQL/MariaDB
    if apt-get install -y $MYSQL_PACKAGE >> "$LOG_FILE" 2>&1; then
        systemctl enable $MYSQL_SERVICE >> "$LOG_FILE" 2>&1
        systemctl start $MYSQL_SERVICE >> "$LOG_FILE" 2>&1
        
        if systemctl is-active --quiet $MYSQL_SERVICE; then
            print_success "MySQL/MariaDB installed and started successfully"
            
            # Secure MySQL/MariaDB installation
            mysql --user=root <<EOF >> "$LOG_FILE" 2>&1
UPDATE mysql.user SET Password=PASSWORD('${MYSQL_ROOT_PASS}') WHERE User='root';
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
FLUSH PRIVILEGES;
EOF
            print_success "MySQL/MariaDB secured successfully"
        else
            print_error "MySQL/MariaDB installed but failed to start"
            exit 1
        fi
    else
        print_error "Failed to install MySQL/MariaDB"
        exit 1
    fi
}

determine_php_version() {
    case $OS_NAME in
        debian)
            case $OS_VERSION in
                8) PHP_VERSION="7.0" ;;
                9) PHP_VERSION="7.0" ;;
                10) PHP_VERSION="7.3" ;;
                11) PHP_VERSION="7.4" ;;
                12) PHP_VERSION="8.2" ;;
            esac
            ;;
        ubuntu)
            case $OS_VERSION in
                20.04) PHP_VERSION="7.4" ;;
                22.04) PHP_VERSION="8.1" ;;
                24.04) PHP_VERSION="8.3" ;;
            esac
            ;;
    esac
}

install_php() {
    determine_php_version
    print_info "Installing PHP $PHP_VERSION and modules..."
    
    # Add PHP repository if needed
    if [[ "$OS_NAME" == "debian" ]]; then
        if [[ "$OS_VERSION" == "8" ]] || [[ "$OS_VERSION" == "9" ]]; then
            # Add Sury PHP repository for older Debian versions
            apt-get install -y apt-transport-https lsb-release ca-certificates >> "$LOG_FILE" 2>&1
            wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg >> "$LOG_FILE" 2>&1
            echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" > /etc/apt/sources.list.d/php.list
            apt-get update -y >> "$LOG_FILE" 2>&1
        fi
    fi
    
    # Install PHP and common modules
    PHP_PACKAGES="php$PHP_VERSION php$PHP_VERSION-cli php$PHP_VERSION-common php$PHP_VERSION-mysql php$PHP_VERSION-gd php$PHP_VERSION-mbstring php$PHP_VERSION-curl php$PHP_VERSION-xml php$PHP_VERSION-zip libapache2-mod-php$PHP_VERSION"
    
    if apt-get install -y $PHP_PACKAGES >> "$LOG_FILE" 2>&1; then
        # Enable PHP module for Apache
        a2enmod php$PHP_VERSION >> "$LOG_FILE" 2>&1
        systemctl restart apache2 >> "$LOG_FILE" 2>&1
        print_success "PHP $PHP_VERSION installed successfully"
    else
        print_error "Failed to install PHP"
        exit 1
    fi
}

configure_firewall() {
    print_info "Configuring firewall..."
    
    # Check if ufw is installed
    if command -v ufw >/dev/null 2>&1; then
        ufw allow 80/tcp >> "$LOG_FILE" 2>&1
        ufw allow 443/tcp >> "$LOG_FILE" 2>&1
        ufw allow 22/tcp >> "$LOG_FILE" 2>&1
        print_success "Firewall configured successfully"
    else
        print_warning "UFW not installed, skipping firewall configuration"
    fi
}

create_test_page() {
    print_info "Creating PHP test page..."
    
    cat > /var/www/html/info.php <<'EOF'
<?php
// Enjyn Skript Service - LAMP Test Page
?>
<!DOCTYPE html>
<html>
<head>
    <title>Enjyn LAMP Test</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f0f0; margin: 40px; }
        .container { background: white; padding: 20px; border-radius: 10px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h1 { color: #5e17eb; }
        .success { color: green; }
        .info { background: #e8f4f8; padding: 10px; border-radius: 5px; margin: 10px 0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Enjyn Skript Service</h1>
        <h2 class="success">✓ LAMP Stack Successfully Installed!</h2>
        <div class="info">
            <h3>System Information:</h3>
            <?php
            echo "<p><strong>PHP Version:</strong> " . phpversion() . "</p>";
            echo "<p><strong>Server Software:</strong> " . $_SERVER['SERVER_SOFTWARE'] . "</p>";
            echo "<p><strong>Server Name:</strong> " . $_SERVER['SERVER_NAME'] . "</p>";
            echo "<p><strong>Document Root:</strong> " . $_SERVER['DOCUMENT_ROOT'] . "</p>";
            ?>
        </div>
        <div class="info">
            <h3>MySQL Connection Test:</h3>
            <?php
            $conn = @mysqli_connect('localhost', 'root', '');
            if ($conn) {
                echo '<p class="success">✓ MySQL connection successful!</p>';
                mysqli_close($conn);
            } else {
                echo '<p>MySQL connection requires authentication (secure)</p>';
            }
            ?>
        </div>
        <p><a href="phpinfo.php">View Detailed PHP Info</a></p>
    </div>
</body>
</html>
EOF
    
    # Create phpinfo page
    cat > /var/www/html/phpinfo.php <<'EOF'
<?php
// Enjyn Skript Service - PHP Info
phpinfo();
?>
EOF
    
    chown www-data:www-data /var/www/html/info.php
    chown www-data:www-data /var/www/html/phpinfo.php
    print_success "Test pages created successfully"
}

show_summary() {
    # Get server IP
    SERVER_IP=$(hostname -I | awk '{print $1}')
    
    echo ""
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}           LAMP Stack Installation Completed!${NC}"
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${CYAN}Installed Components:${NC}"
    echo -e "  • Apache: $(apache2 -v 2>/dev/null | head -n1 | awk '{print $3}')"
    echo -e "  • MySQL: $(mysql --version 2>/dev/null | awk '{print $5}' | sed 's/,$//')"
    echo -e "  • PHP: $PHP_VERSION"
    echo ""
    echo -e "${YELLOW}Important Information:${NC}"
    echo -e "  • MySQL Root Password: ${RED}$MYSQL_ROOT_PASS${NC}"
    echo -e "  • Web Root: /var/www/html/"
    echo -e "  • Apache Config: /etc/apache2/"
    echo -e "  • PHP Config: /etc/php/$PHP_VERSION/"
    echo -e "  • MySQL Config: /etc/mysql/"
    echo -e "  • Installation Log: $LOG_FILE"
    echo ""
    echo -e "${GREEN}Test URLs:${NC}"
    echo -e "  • Apache Default: http://$SERVER_IP/"
    echo -e "  • LAMP Test Page: http://$SERVER_IP/info.php"
    echo -e "  • PHP Info: http://$SERVER_IP/phpinfo.php"
    echo ""
    echo -e "${RED}Security Notes:${NC}"
    echo -e "  • MySQL root password saved in: /root/lamp_credentials.txt"
    echo -e "  • Remove test pages after verification:"
    echo -e "    ${CYAN}rm /var/www/html/info.php${NC}"
    echo -e "    ${CYAN}rm /var/www/html/phpinfo.php${NC}"
    echo ""
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}        Thank you for using Enjyn Skript Service!${NC}"
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
}

# Main execution
main() {
    print_banner
    
    # Initialize log file
    echo "=== Enjyn LAMP Installation Started at $(date) ===" > "$LOG_FILE"
    
    check_root
    detect_os
    
    echo ""
    print_warning "This script will install Apache, MySQL, and PHP (LAMP Stack)"
    echo -n "Do you want to continue? [y/N]: "
    read -r response
    
    if [[ ! "$response" =~ ^[Yy]$ ]]; then
        print_info "Installation cancelled"
        exit 0
    fi
    
    echo ""
    update_system
    install_apache
    install_mysql
    install_php
    configure_firewall
    create_test_page
    
    # Save credentials to file
    cat > /root/lamp_credentials.txt <<EOF
Enjyn Skript Service - LAMP Installation
=======================================
Date: $(date)
Server IP: $(hostname -I | awk '{print $1}')
MySQL Root Password: $MYSQL_ROOT_PASS
=======================================
EOF
    chmod 600 /root/lamp_credentials.txt
    
    show_summary
    
    echo "=== Installation Completed at $(date) ===" >> "$LOG_FILE"
}

# Error handling
set -e
trap 'print_error "An error occurred during installation. Check $LOG_FILE for details."' ERR

# Run main function
main