#!/bin/bash

# Configuration
REPO_URL="https://github.com/DVSwitch/DVSwitch-Dashboard.git"
BRANCH_NAME="Current"
TARGET_DIR="/usr/share/dvswitch"
TEMP_DIR=$(mktemp -d)
APACHE_CONF_FILE="/etc/apache2/conf-available/dvswitch.conf"
APACHE_CONF_LINK="/etc/apache2/conf-enabled/dvswitch.conf"
LOG_FILE="/var/log/dvswitch-install.log"

# Cleanup function
cleanup() {
    if [ -d "$TEMP_DIR" ]; then
        rm -rf "$TEMP_DIR"
    fi
}
trap cleanup EXIT

# Logging function
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

# Error handling function
error_exit() {
    log "ERROR: $1"
    exit 1
}

# Check if running with sudo privileges
check_sudo() {
    if ! sudo -n true 2>/dev/null; then
        error_exit "This script requires sudo privileges. Please run with appropriate permissions."
    fi
}

# Install dependencies
install_dependencies() {
    log "Checking and installing dependencies..."
    
    # Check git
    if ! command -v git &> /dev/null; then
        log "Installing git..."
        sudo apt update && sudo apt install -y git || error_exit "Failed to install git"
    else
        log "git is already installed."
    fi
    
    # Check Apache2
    if ! command -v apache2ctl &> /dev/null; then
        log "Installing Apache2..."
        sudo apt update && sudo apt install -y apache2 || error_exit "Failed to install Apache2"
    else
        log "Apache2 is already installed."
    fi
    
    log "All dependencies satisfied"
}

# Clone and setup dvswitch
setup_dvswitch() {
    log "Cloning repository from $REPO_URL, branch $BRANCH_NAME..."
    if ! git clone -b "$BRANCH_NAME" --single-branch "$REPO_URL" "$TEMP_DIR"; then
        error_exit "Failed to clone repository from $REPO_URL. Make sure the branch '$BRANCH_NAME' exists."
    fi
    log "Repository cloned successfully."
    
    # Verify dvswitch folder exists
    if [ ! -d "$TEMP_DIR/dvswitch" ]; then
        error_exit "dvswitch folder not found in cloned repository"
    fi
    
    # Remove existing directory
    if [ -d "$TARGET_DIR" ]; then
        log "Removing existing directory $TARGET_DIR..."
        sudo rm -rf "$TARGET_DIR" || error_exit "Failed to remove existing directory $TARGET_DIR"
    fi
    
    # Create and copy
    log "Creating target directory $TARGET_DIR..."
    sudo mkdir -p "$TARGET_DIR" || error_exit "Failed to create target directory $TARGET_DIR"
    
    log "Copying dvswitch folder to $TARGET_DIR..."
    sudo cp -r "$TEMP_DIR/dvswitch"/* "$TARGET_DIR/" || error_exit "Failed to copy dvswitch folder"
    
    # CRITICAL: Set proper ownership and permissions
    log "Setting proper ownership and permissions..."
    sudo chown -R root:root "$TARGET_DIR" || error_exit "Failed to set ownership"
    sudo chmod -R u+rwX,go+rX "$TARGET_DIR" || error_exit "Failed to set permissions"
    
    log "DVSwitch files installed successfully"
}

# Configure Apache
configure_apache() {
    log "Setting up Apache configuration for DVSwitch-Dashboard..."
    
    # Create Apache configuration with proper indentation
    sudo tee "$APACHE_CONF_FILE" > /dev/null <<EOF
Alias /dvswitch /usr/share/dvswitch

<Directory /usr/share/dvswitch>
    AllowOverride all
    RewriteEngine On
    RewriteCond %{HTTP:Upgrade} =websocket [NC]
    RewriteRule ^ws/([0-9]+) ws://localhost:\$1 [P,L,QSA]
</Directory>
EOF
    
    log "Apache configuration written to $APACHE_CONF_FILE."
    
    # Enable configuration and modules
    log "Enabling Apache configuration and modules..."
    sudo a2enconf dvswitch.conf
    sudo a2enmod rewrite proxy proxy_http proxy_wstunnel
    
    # Test Apache configuration
    if ! sudo apache2ctl configtest; then
        error_exit "Apache configuration test failed"
    fi
    
    # Reload Apache
    log "Reloading Apache2 service..."
    if ! sudo systemctl reload apache2; then
        error_exit "Failed to reload Apache2. Please check Apache logs for errors."
    fi
    
    log "Apache configured successfully"
}

# Main execution
main() {
    log "Starting DVSwitch installation..."
    check_sudo
    install_dependencies
    setup_dvswitch
    configure_apache
    log "DVSwitch installation completed successfully!"
}

main "$@"
