#!/bin/bash

#################################################################################
#                         Enjyn Skript Service                                  #
#                      Webserver Install Script                                 #
#                   Apache / Nginx with PHP Support                            #
#                     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
WEBSERVER=""
PHP_VERSION=""
OS_VERSION=""
OS_NAME=""
LOG_FILE="/var/log/enjyn_webserver_install.log"
INSTALL_PHP=true
DOMAIN_NAME=""
SSL_INSTALL=false
WWW_USER=""

# Functions
print_banner() {
    clear
    echo -e "${PURPLE}"
    echo "╔═══════════════════════════════════════════════════════════════════╗"
    echo "║                      Enjyn Skript Service                         ║"
    echo "║                    Webserver 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
}

gather_info() {
    echo ""
    print_info "Webserver Selection"
    echo ""
    echo "Which webserver would you like to install?"
    echo "  1) Apache"
    echo "  2) Nginx"
    echo -n "Select webserver [1]: "
    read -r choice
    
    case $choice in
        2) 
            WEBSERVER="nginx"
            WWW_USER="www-data"
            ;;
        *)
            WEBSERVER="apache"
            WWW_USER="www-data"
            ;;
    esac
    
    echo ""
    echo -n "Install PHP? [Y/n]: "
    read -r response
    
    if [[ "$response" =~ ^[Nn]$ ]]; then
        INSTALL_PHP=false
    else
        INSTALL_PHP=true
    fi
    
    echo ""
    echo -n "Enter domain name (leave empty to skip): "
    read -r DOMAIN_NAME
    
    if [[ -n "$DOMAIN_NAME" ]]; then
        echo -n "Install SSL certificate with Let's Encrypt? [y/N]: "
        read -r response
        
        if [[ "$response" =~ ^[Yy]$ ]]; then
            SSL_INSTALL=true
        fi
    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
}

update_system() {
    print_info "Updating system packages..."
    
    export DEBIAN_FRONTEND=noninteractive
    
    if apt-get update -y >> "$LOG_FILE" 2>&1; then
        print_success "System updated successfully"
    else
        print_error "Failed to update system"
        exit 1
    fi
    
    # Install basic tools
    apt-get install -y software-properties-common curl wget >> "$LOG_FILE" 2>&1
}

install_apache() {
    print_info "Installing Apache..."
    
    if apt-get install -y apache2 apache2-utils >> "$LOG_FILE" 2>&1; then
        # Enable necessary modules
        a2enmod rewrite headers expires deflate ssl >> "$LOG_FILE" 2>&1
        
        # Start and enable Apache
        systemctl enable apache2 >> "$LOG_FILE" 2>&1
        systemctl start apache2 >> "$LOG_FILE" 2>&1
        
        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_nginx() {
    print_info "Installing Nginx..."
    
    if apt-get install -y nginx >> "$LOG_FILE" 2>&1; then
        # Start and enable Nginx
        systemctl enable nginx >> "$LOG_FILE" 2>&1
        systemctl start nginx >> "$LOG_FILE" 2>&1
        
        if systemctl is-active --quiet nginx; then
            print_success "Nginx installed and started successfully"
        else
            print_error "Nginx installed but failed to start"
            exit 1
        fi
    else
        print_error "Failed to install Nginx"
        exit 1
    fi
}

install_php() {
    determine_php_version
    print_info "Installing PHP $PHP_VERSION..."
    
    # Add PHP repository if needed for older systems
    if [[ "$OS_NAME" == "debian" ]] && ([[ "$OS_VERSION" == "8" ]] || [[ "$OS_VERSION" == "9" ]]); then
        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
    
    # Base PHP packages
    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 php$PHP_VERSION-bcmath php$PHP_VERSION-json php$PHP_VERSION-opcache"
    
    # Add webserver-specific PHP packages
    if [[ "$WEBSERVER" == "apache" ]]; then
        PHP_PACKAGES="$PHP_PACKAGES libapache2-mod-php$PHP_VERSION"
    else
        PHP_PACKAGES="$PHP_PACKAGES php$PHP_VERSION-fpm"
    fi
    
    # Install PHP
    if apt-get install -y $PHP_PACKAGES >> "$LOG_FILE" 2>&1; then
        if [[ "$WEBSERVER" == "apache" ]]; then
            a2enmod php$PHP_VERSION >> "$LOG_FILE" 2>&1
            systemctl restart apache2 >> "$LOG_FILE" 2>&1
        else
            systemctl enable php$PHP_VERSION-fpm >> "$LOG_FILE" 2>&1
            systemctl start php$PHP_VERSION-fpm >> "$LOG_FILE" 2>&1
        fi
        print_success "PHP $PHP_VERSION installed successfully"
    else
        print_error "Failed to install PHP"
        exit 1
    fi
}

configure_apache_vhost() {
    print_info "Configuring Apache virtual host for $DOMAIN_NAME..."
    
    # Create directory
    mkdir -p /var/www/$DOMAIN_NAME/public_html
    
    # Create virtual host file
    cat > /etc/apache2/sites-available/$DOMAIN_NAME.conf <<EOF
<VirtualHost *:80>
    ServerName $DOMAIN_NAME
    ServerAlias www.$DOMAIN_NAME
    ServerAdmin webmaster@$DOMAIN_NAME
    DocumentRoot /var/www/$DOMAIN_NAME/public_html
    
    <Directory /var/www/$DOMAIN_NAME/public_html>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN_NAME-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN_NAME-access.log combined
</VirtualHost>
EOF
    
    # Enable site
    a2ensite $DOMAIN_NAME.conf >> "$LOG_FILE" 2>&1
    systemctl reload apache2 >> "$LOG_FILE" 2>&1
    
    print_success "Virtual host configured"
}

configure_nginx_vhost() {
    print_info "Configuring Nginx server block for $DOMAIN_NAME..."
    
    # Create directory
    mkdir -p /var/www/$DOMAIN_NAME/public_html
    
    # Create server block
    if [[ "$INSTALL_PHP" == true ]]; then
        cat > /etc/nginx/sites-available/$DOMAIN_NAME <<EOF
server {
    listen 80;
    listen [::]:80;
    
    server_name $DOMAIN_NAME www.$DOMAIN_NAME;
    root /var/www/$DOMAIN_NAME/public_html;
    index index.php index.html index.htm;
    
    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php$PHP_VERSION-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
    
    location ~ /\. {
        deny all;
    }
    
    access_log /var/log/nginx/$DOMAIN_NAME-access.log;
    error_log /var/log/nginx/$DOMAIN_NAME-error.log;
}
EOF
    else
        cat > /etc/nginx/sites-available/$DOMAIN_NAME <<EOF
server {
    listen 80;
    listen [::]:80;
    
    server_name $DOMAIN_NAME www.$DOMAIN_NAME;
    root /var/www/$DOMAIN_NAME/public_html;
    index index.html index.htm;
    
    location / {
        try_files \$uri \$uri/ =404;
    }
    
    location ~ /\.ht {
        deny all;
    }
    
    location ~ /\. {
        deny all;
    }
    
    access_log /var/log/nginx/$DOMAIN_NAME-access.log;
    error_log /var/log/nginx/$DOMAIN_NAME-error.log;
}
EOF
    fi
    
    # Enable site
    ln -s /etc/nginx/sites-available/$DOMAIN_NAME /etc/nginx/sites-enabled/
    nginx -t >> "$LOG_FILE" 2>&1
    systemctl reload nginx >> "$LOG_FILE" 2>&1
    
    print_success "Server block configured"
}

install_ssl() {
    print_info "Installing SSL certificate..."
    
    # Install certbot
    if [[ "$OS_NAME" == "debian" ]] && [[ "$OS_VERSION" == "8" ]]; then
        print_warning "Let's Encrypt not supported on Debian 8"
        return
    fi
    
    apt-get install -y certbot >> "$LOG_FILE" 2>&1
    
    if [[ "$WEBSERVER" == "apache" ]]; then
        apt-get install -y python3-certbot-apache >> "$LOG_FILE" 2>&1
        certbot --apache -d $DOMAIN_NAME -d www.$DOMAIN_NAME --non-interactive --agree-tos --register-unsafely-without-email >> "$LOG_FILE" 2>&1
    else
        apt-get install -y python3-certbot-nginx >> "$LOG_FILE" 2>&1
        certbot --nginx -d $DOMAIN_NAME -d www.$DOMAIN_NAME --non-interactive --agree-tos --register-unsafely-without-email >> "$LOG_FILE" 2>&1
    fi
    
    if [[ $? -eq 0 ]]; then
        print_success "SSL certificate installed"
    else
        print_warning "SSL installation failed - please run certbot manually"
    fi
}

create_test_pages() {
    print_info "Creating test pages..."
    
    if [[ -n "$DOMAIN_NAME" ]]; then
        TEST_DIR="/var/www/$DOMAIN_NAME/public_html"
    else
        if [[ "$WEBSERVER" == "apache" ]]; then
            TEST_DIR="/var/www/html"
        else
            TEST_DIR="/var/www/html"
        fi
    fi
    
    # Create index page
    cat > $TEST_DIR/index.html <<EOF
<!DOCTYPE html>
<html>
<head>
    <title>Enjyn Webserver</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f0f0; margin: 0; padding: 0; }
        .container { max-width: 800px; margin: 50px auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }
        h1 { color: #5e17eb; text-align: center; }
        .success { color: green; text-align: center; font-size: 24px; }
        .info { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 20px 0; }
        .logo { text-align: center; font-size: 48px; margin-bottom: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="logo">🚀</div>
        <h1>Enjyn Skript Service</h1>
        <p class="success">✓ Webserver Successfully Installed!</p>
        <div class="info">
            <h3>Server Information:</h3>
            <p><strong>Webserver:</strong> $WEBSERVER</p>
            <p><strong>Operating System:</strong> $OS_NAME $OS_VERSION</p>
            <p><strong>Document Root:</strong> $TEST_DIR</p>
        </div>
        <div class="info">
            <h3>Next Steps:</h3>
            <ul>
                <li>Upload your website files to the document root</li>
                <li>Configure your DNS settings if using a domain</li>
                <li>Install SSL certificate for HTTPS</li>
                <li>Configure firewall rules</li>
            </ul>
        </div>
    </div>
</body>
</html>
EOF

    if [[ "$INSTALL_PHP" == true ]]; then
        # Create PHP info page
        cat > $TEST_DIR/info.php <<'EOF'
<?php
// Enjyn Skript Service - PHP Info Page
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP Info - Enjyn</title>
    <style>
        body { font-family: Arial, sans-serif; background: #f0f0f0; margin: 0; padding: 0; }
        .container { max-width: 800px; margin: 50px auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 0 20px rgba(0,0,0,0.1); }
        h1 { color: #5e17eb; text-align: center; }
        .success { color: green; }
        .info { background: #e8f4f8; padding: 15px; border-radius: 5px; margin: 20px 0; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Enjyn PHP Information</h1>
        <div class="info">
            <h3>PHP Configuration:</h3>
            <?php
            echo "<p><strong>PHP Version:</strong> " . phpversion() . "</p>";
            echo "<p><strong>Server Software:</strong> " . $_SERVER['SERVER_SOFTWARE'] . "</p>";
            echo "<p><strong>Document Root:</strong> " . $_SERVER['DOCUMENT_ROOT'] . "</p>";
            echo "<p><strong>Server API:</strong> " . php_sapi_name() . "</p>";
            ?>
            <p><a href="phpinfo.php">View Detailed PHP Info</a></p>
        </div>
    </div>
</body>
</html>
EOF

        # Create phpinfo page
        cat > $TEST_DIR/phpinfo.php <<'EOF'
<?php
// Enjyn Skript Service - Detailed PHP Info
phpinfo();
?>
EOF
    fi
    
    # Set permissions
    chown -R $WWW_USER:$WWW_USER $TEST_DIR
    
    print_success "Test pages created"
}

configure_firewall() {
    print_info "Configuring firewall..."
    
    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
        print_success "Firewall configured for HTTP/HTTPS"
    else
        print_warning "UFW not installed, please manually configure firewall"
    fi
}

show_summary() {
    SERVER_IP=$(hostname -I | awk '{print $1}')
    
    echo ""
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
    echo -e "${GREEN}         Webserver Installation Completed!${NC}"
    echo -e "${PURPLE}════════════════════════════════════════════════════════════════════${NC}"
    echo ""
    echo -e "${CYAN}Installed Components:${NC}"
    echo -e "  • Webserver: $WEBSERVER"
    if [[ "$INSTALL_PHP" == true ]]; then
        echo -e "  • PHP: $PHP_VERSION"
    fi
    echo ""
    
    echo -e "${CYAN}Configuration:${NC}"
    if [[ "$WEBSERVER" == "apache" ]]; then
        echo -e "  • Config Directory: /etc/apache2/"
        echo -e "  • Sites Available: /etc/apache2/sites-available/"
        echo -e "  • Log Directory: /var/log/apache2/"
    else
        echo -e "  • Config Directory: /etc/nginx/"
        echo -e "  • Sites Available: /etc/nginx/sites-available/"
        echo -e "  • Log Directory: /var/log/nginx/"
    fi
    
    if [[ "$INSTALL_PHP" == true ]]; then
        echo -e "  • PHP Config: /etc/php/$PHP_VERSION/"
        if [[ "$WEBSERVER" == "nginx" ]]; then
            echo -e "  • PHP-FPM Socket: /var/run/php/php$PHP_VERSION-fpm.sock"
        fi
    fi
    
    echo ""
    echo -e "${GREEN}Access URLs:${NC}"
    if [[ -n "$DOMAIN_NAME" ]]; then
        echo -e "  • Domain: http://$DOMAIN_NAME/"
        if [[ "$SSL_INSTALL" == true ]]; then
            echo -e "  • Secure: https://$DOMAIN_NAME/"
        fi
        echo -e "  • Document Root: /var/www/$DOMAIN_NAME/public_html/"
    else
        echo -e "  • Default: http://$SERVER_IP/"
        echo -e "  • Document Root: /var/www/html/"
    fi
    
    if [[ "$INSTALL_PHP" == true ]]; then
        if [[ -n "$DOMAIN_NAME" ]]; then
            echo -e "  • PHP Info: http://$DOMAIN_NAME/info.php"
        else
            echo -e "  • PHP Info: http://$SERVER_IP/info.php"
        fi
    fi
    
    echo ""
    echo -e "${GREEN}Service Commands:${NC}"
    if [[ "$WEBSERVER" == "apache" ]]; then
        echo -e "  • Restart: ${CYAN}systemctl restart apache2${NC}"
        echo -e "  • Status: ${CYAN}systemctl status apache2${NC}"
        echo -e "  • Test Config: ${CYAN}apache2ctl configtest${NC}"
    else
        echo -e "  • Restart: ${CYAN}systemctl restart nginx${NC}"
        echo -e "  • Status: ${CYAN}systemctl status nginx${NC}"
        echo -e "  • Test Config: ${CYAN}nginx -t${NC}"
    fi
    
    if [[ "$INSTALL_PHP" == true ]] && [[ "$WEBSERVER" == "nginx" ]]; then
        echo -e "  • PHP-FPM Restart: ${CYAN}systemctl restart php$PHP_VERSION-fpm${NC}"
    fi
    
    echo ""
    echo -e "${RED}Security Notes:${NC}"
    echo -e "  • Remove test pages after verification:"
    echo -e "    ${CYAN}rm $TEST_DIR/info.php${NC}"
    echo -e "    ${CYAN}rm $TEST_DIR/phpinfo.php${NC}"
    echo -e "  • Configure firewall rules"
    echo -e "  • Set up regular backups"
    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 Webserver Installation Started at $(date) ===" > "$LOG_FILE"
    
    check_root
    detect_os
    gather_info
    
    echo ""
    print_info "Starting installation..."
    echo ""
    
    update_system
    
    # Install webserver
    if [[ "$WEBSERVER" == "apache" ]]; then
        install_apache
    else
        install_nginx
    fi
    
    # Install PHP if requested
    if [[ "$INSTALL_PHP" == true ]]; then
        install_php
    fi
    
    # Configure virtual host if domain provided
    if [[ -n "$DOMAIN_NAME" ]]; then
        if [[ "$WEBSERVER" == "apache" ]]; then
            configure_apache_vhost
        else
            configure_nginx_vhost
        fi
        
        # Install SSL if requested
        if [[ "$SSL_INSTALL" == true ]]; then
            install_ssl
        fi
    fi
    
    create_test_pages
    configure_firewall
    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