#!/bin/bash
# NebiDE Shell Configuration Manager
# Handles configuration application for various NebiDE components

CONFIG_FILE="$HOME/.config/NebiSoft/firstusersetup.json"
OOBE_DIR="/System/NebiDE Files/firstSetupUtil"
VM_TYPE=$(systemd-detect-virt)

echo "[shellconf] XDG_CURRENT_DESKTOP=$XDG_CURRENT_DESKTOP"
echo "[shellconf] XDG_SESSION_DESKTOP=$XDG_SESSION_DESKTOP"
echo "[shellconf] DESKTOP_SESSION=$DESKTOP_SESSION"
echo "[shellconf] DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS"

run_oobe() {
    echo "OOBE not completed, launching First Setup Utility..."

    # NebiDE 3.1+ will skip intro video (which causes crashes on the VM)
    # if its running on the VM. Not removing the info however
    # i'll go commenting the "force software rendering" thing.
    if [[ "$VM_TYPE" != "none" ]]; then
        # export LIBGL_ALWAYS_SOFTWARE=1
        echo "[nebide] VM detected: $VM_TYPE"
    else
        echo "[nebide] Running on bare metal"
    fi
    # DISABLED nebide-disable-dbusactivatable
    cd "$OOBE_DIR" && ./nebide-oobe
    # unset LIBGL_ALWAYS_SOFTWARE
}

# Check if config file exists
if [ ! -f "$CONFIG_FILE" ]; then
    run_oobe
fi

# Check if oobe_done key exists and is true
if grep -q '"oobe_done"[[:space:]]*:[[:space:]]*true' "$CONFIG_FILE"; then
    echo "OOBE already completed, skipping..."
else
    run_oobe
fi

export LC_ALL=en_US.UTF-8

# Configuration paths
CONFIG_DIR="$HOME/.config/NebiSoft"
SHELL_DATA_DIR="$CONFIG_DIR/NebiDE.shell.data"
LAYOUT_DIR="$SHELL_DATA_DIR/layout"
GTK4_CONFIG_DIR="$HOME/.config/gtk-4.0"

# Log function
log() {
    echo "[shellconf] $1"
}

# Apply panel layout configuration
apply_layout() {
    log "Applying panel layout configuration..."
    
    # Navigate to shell data directory
    cd "$SHELL_DATA_DIR" || exit 1
    
    # Kill any existing panelconf.gen.py processes
    pkill -f "python3 .*panelconf\.gen\.py" || true
    
    # Kill any existing waybar instances
    killall -s KILL waybar
    pkill -f "/usr/libexec/geoclue-2.0/demos/agent"
    
    # Run the panel configuration generator
    cd "$LAYOUT_DIR" || exit 1
    nohup python3 ./panelconf.gen.py > /dev/null 2>&1 &
}

# Apply window manager configuration
apply_wm_config() {
    log "Applying window manager configuration..."
    cd "$SHELL_DATA_DIR" || exit 1
    python3 ./modconf.wm.py
}

# Apply input configuration
apply_input_config() {
    log "Applying input configuration..."
    cd "$SHELL_DATA_DIR" || exit 1
    python3 ./modconf.input.py
}

# Apply key bindings configuration
apply_bindings_config() {
    log "Applying key bindings configuration..."
    cd "$SHELL_DATA_DIR" || exit 1
    python3 ./modconf.bindings.py
}

# Apply GTK theme configuration
apply_gtk_theme() {
    log "Applying GTK theme configuration..."
    
    # Get current theme settings
    THEME=$(gsettings get org.gnome.desktop.interface gtk-theme | tr -d "'")
    COLOR_SCHEME=$(gsettings get org.gnome.desktop.interface color-scheme | tr -d "'")
    
    # Determine if theme is dark or light
    if [[ "$COLOR_SCHEME" == *"dark"* ]] || [[ "$THEME" == *"Dark"* ]] || [[ "$THEME" == *"dark"* ]]; then
        VARIANT="Dark"
    else
        VARIANT="Light"
    fi
    
    log "Theme variant: $VARIANT"
    
    # Configure GTK4 (copy appropriate CSS file)
    if [ -f "$GTK4_CONFIG_DIR/gtk-$VARIANT.css" ]; then
        log "Applying GTK4 theme ($VARIANT variant)..."
        cp "$GTK4_CONFIG_DIR/gtk-$VARIANT.css" "$GTK4_CONFIG_DIR/gtk.css"
    fi
    
    # Apply GTK settings via gsettings
    # These settings are already set from elsewhere, so we don't need to change them
    # Just log what we have
    log "Current GTK theme: $(gsettings get org.gnome.desktop.interface gtk-theme)"
    log "Current icon theme: $(gsettings get org.gnome.desktop.interface icon-theme)"
    log "Current font: $(gsettings get org.gnome.desktop.interface font-name)"
    
    # Check if WM needs updating due to GTK theme change
    if grep -q "gtk_manages_titlebars = true" "$SHELL_DATA_DIR/init.conf"; then
        log "GTK manages titlebars is enabled, updating WM configuration..."
        apply_wm_config
    fi
    
    source ~/.config/NebiSoft/NebiDE.shell.conf
    
    gsettings set org.gnome.desktop.wm.preferences button-layout "$(echo "'"$titlebarbtns"'" | sed 's/://;s/i//g;s/t//g;s/m/minimize,/g;s/x/maximize,/g;s/c/close,/g;s/,:/:/g;s/,$//' | sed "s/,'$/'/")"
}

apply_icon_theme() {
    log "Applying icon theme configuration..."
    apply_layout
}

# Restart applets
restart_applets() {
    log "Restarting NebiDE applets..."
    
    # Restart input language applet
    if pgrep -f "nebide-inputlang-applet" > /dev/null; then
        log "Restarting input language applet..."
        killall nebide-inputlang-applet
        nohup nebide-inputlang-applet > /dev/null 2>&1 &
    else
        log "Starting input language applet..."
        nohup nebide-inputlang-applet > /dev/null 2>&1 &
    fi
    
    # Restart Bluetooth applet
    if pgrep -f "nebide-inputlang-applet" > /dev/null; then
        log "Restarting Bluetooth  applet..."
        killall blueman-applet
        nohup blueman-applet > /dev/null 2>&1 &
    else
        log "Starting Bluetooth  applet..."
        nohup blueman-applet > /dev/null 2>&1 &
    fi
    
}

restart_comps() {
    killall -s KILL nebide-qs nebide-osd nebide-launcher
    LC_ALL="$LANG" nohup nebide-qs > /dev/null 2>&1 &
    LC_ALL="$LANG" nohup nebide-osd > /dev/null 2>&1 &
    LC_ALL="$LANG" nohup nebide-launcher > /dev/null 2>&1 &
}

# Restart system daemons/tools
restart_system_tools() {
    log "Restarting NebiDE system tools..."
    
    # Restart power manager
    if pgrep -f "nebide-pm" > /dev/null; then
        log "Restarting power manager daemon..."
        killall nebide-pm
        sleep 0.5  # Allow time for proper shutdown
        nohup nebide-pm > /dev/null 2>&1 &
    else
        log "Starting power manager daemon..."
        nohup nebide-pm > /dev/null 2>&1 &
    fi
}

# Apply all configurations (used during init)
apply_all() {
    log "Initializing NebiDE shell with all configurations..."
    
    # First apply base configurations
    apply_wm_config
    apply_input_config
    apply_bindings_config
    apply_gtk_theme
    
    # Then start or restart services
    restart_comps
    apply_layout
    sleep 3
    restart_applets
    restart_system_tools
    nebide-shell-autostart
    
    log "NebiDE initialization complete."
}

# Main logic based on arguments
case "$1" in
    "wm")
        apply_wm_config
        ;;
    "input")
        apply_input_config
        ;;
    "bindings")
        apply_bindings_config
        ;;
    "gtk")
        apply_gtk_theme
        ;;
    "icon")
        apply_icon_theme
        ;;
    "layout" | "panel")
        apply_layout
        ;;
    "applets")
        restart_applets
        ;;
    "components")
        restart_comps
        ;;
    "tools" | "daemons")
        restart_system_tools
        ;;
    *)
        # No specific argument, apply all configurations
        apply_all
        ;;
esac

exit 0
