#!/bin/bash

# Exit on error, unset variable usage, and error in a pipeline
set -euo pipefail

# Define color variables
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No color

# Function to print messages in color
info() { echo -e "${BLUE}[INFO]${NC} $1"; }
success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; exit 1; }

# Check for root privileges
if [[ "$EUID" -ne 0 ]]; then
    error "This script must be run as root. Use 'sudo ./installation.sh'"
fi

# Update and install necessary packages
info "Updating package list and installing necessary packages..."
sudo apt update && sudo apt install -y git gh apache2 sqlite3 php php-sqlite3 python3 python3-pip jq autossh i2c-tools python3-smbus python3-rpi.gpio || error "Failed to install required packages."

# Install Python libraries
info "Installing Python libraries..."
sudo pip3 install pyserial requests adafruit-circuitpython-bme280 crcmod psutil gpiozero ntplib adafruit-circuitpython-ads1x15 nsrt-mk3-dev pytz --break-system-packages || error "Failed to install Python libraries."

# Clone the repository (check if it exists first)
REPO_DIR="/var/www/nebuleair_pro_4g"
if [[ -d "$REPO_DIR" ]]; then
    warning "Repository already exists. Will update instead of clone."
    # Save current directory
    local current_dir=$(pwd)
    # Navigate to repository directory
    cd "$REPO_DIR"
    # Stash any local changes
    sudo git stash || warning "Failed to stash local changes"
    # Pull latest changes
    sudo git pull || error "Failed to pull latest changes"
    # Return to original directory
    cd "$current_dir"
    success "Repository updated successfully!"
else
    info "Cloning the NebuleAir Pro 4G repository..."
    sudo git clone http://gitea.aircarto.fr/PaulVua/nebuleair_pro_4g.git "$REPO_DIR" || error "Failed to clone repository."
fi

# Set up repository files and permissions
info "Setting up repository files and permissions..."
sudo mkdir -p "$REPO_DIR/logs"
sudo touch "$REPO_DIR/logs/app.log" "$REPO_DIR/logs/master.log" "$REPO_DIR/logs/master_errors.log" "$REPO_DIR/wifi_list.csv"
sudo chmod -R 755 "$REPO_DIR/"
sudo chown -R www-data:www-data "$REPO_DIR/"
sudo git config --global core.fileMode false
#sudo git -C /var/www/nebuleair_pro_4g config core.fileMode false
sudo git config --global --add safe.directory "$REPO_DIR"

# Set up cron jobs (ensure file exists first)
info "Setting up cron jobs..."
if [[ -f "$REPO_DIR/cron_jobs" ]]; then
    sudo crontab "$REPO_DIR/cron_jobs"
    success "Cron jobs set up successfully."
else
    warning "Cron jobs file not found. Skipping."
fi

# Create databases
info "Creating databases..."
if [[ -f "$REPO_DIR/sqlite/create_db.py" ]]; then
    sudo /usr/bin/python3 "$REPO_DIR/sqlite/create_db.py" || error "Failed to create databases."
    success "Databases created successfully."
else
    warning "Database creation script not found."
fi

# Set config
info "Set config..."
if [[ -f "$REPO_DIR/sqlite/set_config.py" ]]; then
    sudo /usr/bin/python3 "$REPO_DIR/sqlite/set_config.py" || error "Failed to set config."
    success "Databases set configuration successfully."
else
    warning "Database set configuration script not found."
fi

# Configure Apache
info "Configuring Apache..."
APACHE_CONF="/etc/apache2/sites-available/000-default.conf"
if grep -q "DocumentRoot /var/www/nebuleair_pro_4g" "$APACHE_CONF"; then
    warning "Apache DocumentRoot already set. Skipping."
else
    sudo sed -i 's|DocumentRoot /var/www/html|DocumentRoot /var/www/nebuleair_pro_4g|' "$APACHE_CONF"
    success "Apache DocumentRoot updated."
fi

# Enable AllowOverride for .htaccess (needed for PHP upload limits)
APACHE_MAIN_CONF="/etc/apache2/apache2.conf"
if grep -q "AllowOverride All" "$APACHE_MAIN_CONF"; then
    warning "AllowOverride already configured. Skipping."
else
    # Replace AllowOverride None with AllowOverride All for /var/www/
    sudo sed -i '/<Directory \/var\/www\/>/,/<\/Directory>/ s/AllowOverride None/AllowOverride All/' "$APACHE_MAIN_CONF"
    success "AllowOverride All enabled for /var/www/."
fi

# Also increase PHP limits directly in php.ini as fallback
PHP_INI=$(php -r "echo php_ini_loaded_file();" 2>/dev/null)
if [[ -n "$PHP_INI" ]]; then
    sudo sed -i 's/upload_max_filesize = .*/upload_max_filesize = 50M/' "$PHP_INI"
    sudo sed -i 's/post_max_size = .*/post_max_size = 55M/' "$PHP_INI"
    success "PHP upload limits set to 50M in $PHP_INI"
fi

sudo systemctl reload apache2
success "Apache configuration updated and reloaded."

# Add sudo authorization (prevent duplicate entries)
info "Setting up sudo authorization..."
SUDOERS_FILE="/etc/sudoers"

# First, fix any existing syntax errors
if sudo visudo -c 2>&1 | grep -q "syntax error"; then
    warning "Syntax error detected in sudoers file. Attempting to fix..."
    # Remove the problematic line if it exists
    sudo sed -i '/www-data ALL=(ALL) NOPASSWD: \/usr\/bin\/python3 \* www-data/d' "$SUDOERS_FILE"
fi

# Add proper sudo rules (each on a separate line)
if ! sudo grep -q "/usr/bin/nmcli" "$SUDOERS_FILE"; then
    # Create a temporary file with the new rules
    cat <<EOF | sudo tee /tmp/sudoers_additions > /dev/null
# NebuleAir Pro 4G sudo rules
ALL ALL=(ALL) NOPASSWD: /usr/bin/nmcli, /usr/sbin/reboot
www-data ALL=(ALL) NOPASSWD: /usr/bin/git pull
www-data ALL=(ALL) NOPASSWD: /usr/bin/ssh
www-data ALL=(ALL) NOPASSWD: /usr/bin/python3 *
www-data ALL=(ALL) NOPASSWD: /bin/systemctl *
www-data ALL=(ALL) NOPASSWD: /usr/bin/pkill *
www-data ALL=(ALL) NOPASSWD: /var/www/nebuleair_pro_4g/*
EOF
    
    # Validate the temporary file
    if sudo visudo -c -f /tmp/sudoers_additions; then
        # Append to sudoers if valid
        sudo cat /tmp/sudoers_additions >> "$SUDOERS_FILE"
        success "Sudo authorization added."
    else
        error "Failed to add sudo rules - syntax validation failed."
    fi
    
    # Clean up
    sudo rm -f /tmp/sudoers_additions
else
    warning "Sudo authorization already set. Skipping."
fi

# Validate sudoers file after changes
if ! sudo visudo -c; then
    error "Sudoers file has syntax errors! Please fix manually with 'sudo visudo'"
fi

# Open all UART serial ports and disable HDMI + Bluetooth (avoid duplication)
info "Configuring UART serial ports and disabling Bluetooth to save power..."
if ! grep -q "enable_uart=1" /boot/firmware/config.txt; then
    echo -e "\nenable_uart=1\ndtoverlay=uart0\ndtoverlay=uart1\ndtoverlay=uart2\ndtoverlay=uart3\ndtoverlay=uart4\ndtoverlay=uart5\n\n# Disable Bluetooth to save power (~20-30mA)\ndtoverlay=disable-bt" | sudo tee -a /boot/firmware/config.txt > /dev/null
    success "UART configuration, HDMI and Bluetooth disable added."
else
    warning "UART configuration already set. Skipping."
fi

# Ensure correct permissions for serial devices
info "Setting permissions for serial devices..."
sudo chmod 666 /dev/ttyAMA* || warning "Failed to set permissions for /dev/ttyAMA*"

# Enable I2C ports
info "Enabling I2C ports..."
sudo raspi-config nonint do_i2c 0
success "I2C ports enabled."

# Final sudoers check
if sudo visudo -c; then
    success "Sudoers file is valid."
else
    error "Sudoers file has errors! System may not function correctly."
fi

# Completion message
success "Setup completed successfully!"
info "System will reboot in 5 seconds..."
sleep 5
sudo reboot
