#!/bin/bash

# =============================================================================
# Dell XPS 13 9350 Ubuntu 24.04.2 LTS Hardware Optimization Script
# PURPOSE: Install drivers and optimizations specific to Dell XPS 13 9350 hardware
# LAST UPDATED: August 22, 2025
# COMPATIBILITY: Ubuntu 24.04.2 LTS on Dell XPS 13 9350
# KEY FIX: Disabled USB autosuspend to prevent mouse/hub disconnection issues
# =============================================================================

set -e  # Exit on error

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}Dell XPS 13 9350 Hardware Setup Script${NC}"
echo -e "${BLUE}========================================${NC}"
echo ""

# =============================================================================
# INTEL GRAPHICS DRIVERS & ACCELERATION
# =============================================================================
# The XPS 13 9350 uses Intel Iris Xe graphics (12th gen Intel CPU)
# These packages ensure proper hardware acceleration and video decode/encode
echo -e "${GREEN}Installing Intel Graphics drivers and acceleration...${NC}"
sudo apt update
sudo apt install -y intel-media-va-driver-non-free \
    i965-va-driver \
    vainfo \
    mesa-utils \
    intel-gpu-tools

# Intel GuC/HuC firmware for better GPU performance
# Enables GPU firmware loading for improved power management and performance
sudo apt install -y linux-firmware

# =============================================================================
# THERMAL MANAGEMENT & POWER OPTIMIZATION
# =============================================================================
# TLP provides advanced power management specifically tuned for laptops
# Critical for battery life on XPS 13 which can run hot
echo -e "${GREEN}Installing TLP for advanced power management...${NC}"
sudo apt install -y tlp tlp-rdw

# Configure TLP to NOT suspend USB devices (prevents mouse/hub issues)
# This is critical for users with USB docks, hubs, or external mice
sudo tee /etc/tlp.d/50-usb-no-suspend.conf > /dev/null <<EOF
# Disable USB autosuspend to prevent mouse/hub disconnection issues
# This fixes the common problem where USB devices stop working after login
USB_AUTOSUSPEND=0

# Exclude all USB devices from autosuspend
USB_BLACKLIST_PHONE=0
USB_BLACKLIST_PRINTER=0
USB_BLACKLIST_WWAN=0

# Keep USB controllers active
RUNTIME_PM_ON_AC=on
RUNTIME_PM_ON_BAT=on

# Disable USB power management entirely
USB_AUTOSUSPEND_DISABLE_ON_SHUTDOWN=1
EOF

# Start TLP service
sudo tlp start
sudo systemctl enable tlp.service

# PowerTOP helps identify power-hungry processes and tune system for battery life
echo -e "${GREEN}Installing PowerTOP for power consumption analysis...${NC}"
sudo apt install -y powertop

# NOTE: We do NOT enable PowerTOP auto-tune as it causes USB device issues
# Users can manually run 'sudo powertop' to analyze power usage
# or 'sudo powertop --auto-tune' for one-time optimization (may affect USB)
echo -e "${YELLOW}PowerTOP installed for manual power analysis only${NC}"
echo -e "${YELLOW}Auto-tune is NOT enabled to prevent USB disconnection issues${NC}"

# Thermald provides thermal management to prevent throttling
# Essential for XPS 13 9350 which can thermal throttle under load
echo -e "${GREEN}Installing thermald for thermal management...${NC}"
sudo apt install -y thermald
sudo systemctl enable thermald
sudo systemctl start thermald

# =============================================================================
# TOUCHPAD & INPUT DEVICE OPTIMIZATION
# =============================================================================
# The XPS 13 has a precision touchpad that benefits from libinput improvements
echo -e "${GREEN}Optimizing touchpad settings...${NC}"

# Install libinput tools for touchpad management
sudo apt install -y libinput-tools xserver-xorg-input-libinput

# Create X11 config directory if it doesn't exist
sudo mkdir -p /etc/X11/xorg.conf.d/

# Create custom touchpad configuration for better palm detection and gestures
sudo tee /etc/X11/xorg.conf.d/30-touchpad.conf > /dev/null <<EOF
Section "InputClass"
    Identifier "touchpad"
    Driver "libinput"
    MatchIsTouchpad "on"
    Option "Tapping" "on"
    Option "TappingButtonMap" "lrm"
    Option "ClickMethod" "clickfinger"
    Option "NaturalScrolling" "true"
    Option "ScrollMethod" "twofinger"
    Option "DisableWhileTyping" "true"
    Option "PalmDetection" "true"
    Option "PalmMinWidth" "8"
    Option "PalmMinZ" "100"
EndSection
EOF

# =============================================================================
# WIFI & BLUETOOTH OPTIMIZATION
# =============================================================================
# XPS 13 9350 typically uses Intel AX211 or similar Intel WiFi 6E cards
echo -e "${GREEN}Optimizing WiFi and Bluetooth...${NC}"

# Modern kernels (6.x+) have excellent built-in Intel WiFi support
# Just ensure firmware is up to date
sudo apt install -y linux-firmware bluez-firmware

# Disable WiFi power management for more stable connection
# This prevents WiFi disconnections but slightly increases power usage
sudo tee /etc/NetworkManager/conf.d/wifi-powersave-off.conf > /dev/null <<EOF
[connection]
wifi.powersave = 2
EOF

# =============================================================================
# AUDIO ENHANCEMENTS
# =============================================================================
# XPS 13 9350 uses Realtek ALC audio codec that benefits from these tweaks
echo -e "${GREEN}Installing audio enhancements...${NC}"

# SOF (Sound Open Firmware) for better audio support on modern Intel systems
sudo apt install -y firmware-sof-signed

# PulseAudio equalizer for better audio quality from small laptop speakers
sudo apt install -y pulseaudio-equalizer

# Enable high quality audio resampling
sudo tee -a /etc/pulse/daemon.conf > /dev/null <<EOF

# High quality resampling for XPS 13 audio
resample-method = speex-float-10
default-sample-format = float32le
default-sample-rate = 48000
alternate-sample-rate = 44100
EOF

# =============================================================================
# DISPLAY & SCALING OPTIMIZATION
# =============================================================================
# XPS 13 9350 often has high DPI displays (FHD+ or UHD+)
echo -e "${GREEN}Configuring display scaling...${NC}"

# Install tools for display management
sudo apt install -y arandr autorandr

# Enable fractional scaling in GNOME (if using GNOME)
if [ "$XDG_CURRENT_DESKTOP" == "ubuntu:GNOME" ] || [ "$XDG_CURRENT_DESKTOP" == "GNOME" ]; then
    gsettings set org.gnome.mutter experimental-features "['scale-monitor-framebuffer']"
    echo -e "${YELLOW}Fractional scaling enabled in GNOME settings${NC}"
fi

# =============================================================================
# SSD OPTIMIZATION
# =============================================================================
# XPS 13 9350 uses NVMe SSDs that benefit from TRIM and optimization
echo -e "${GREEN}Optimizing SSD performance...${NC}"

# Enable weekly TRIM for SSD longevity
sudo systemctl enable fstrim.timer
sudo systemctl start fstrim.timer

# Install NVMe tools for SSD health monitoring
sudo apt install -y nvme-cli smartmontools

# Reduce swappiness for better SSD lifespan and performance
echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf

# =============================================================================
# FIRMWARE UPDATES
# =============================================================================
# Dell provides firmware updates through Linux Vendor Firmware Service
echo -e "${GREEN}Installing firmware update tools...${NC}"

# fwupd allows updating Dell firmware/BIOS from Linux
sudo apt install -y fwupd fwupd-signed

# Check for firmware updates (but don't auto-install)
echo -e "${YELLOW}Checking for firmware updates...${NC}"
sudo fwupdmgr refresh --force
sudo fwupdmgr get-updates || echo "No firmware updates available"

# =============================================================================
# DELL-SPECIFIC UTILITIES
# =============================================================================
echo -e "${GREEN}Installing Dell-specific utilities...${NC}"

# Dell Command Configure for Linux (if available in repos)
# This allows configuring BIOS settings from Linux
echo -e "${YELLOW}Attempting to install Dell SMBIOS utilities...${NC}"
sudo apt install -y libsmbios-utils 2>/dev/null || {
    echo -e "${YELLOW}Dell SMBIOS utilities not available - skipping${NC}"
}

# Install Dell fan control utility for manual fan management if needed
# Useful during heavy workloads to prevent thermal throttling
if ! command -v i8kctl &> /dev/null; then
    sudo apt install -y i8kutils
    
    # Configure i8kmon for automatic fan control
    sudo tee /etc/i8kmon.conf > /dev/null <<EOF
# Temperature thresholds for fan control (Celsius)
set config(0) {{0 0}  -1  55  -1  55}
set config(1) {{1 1}  50  60  50  60}
set config(2) {{2 2}  55  65  55  65}
set config(3) {{3 3}  60  75  60  75}
EOF
    
    sudo systemctl enable i8kmon
    sudo systemctl start i8kmon
fi

# =============================================================================
# BATTERY LIFE OPTIMIZATION
# =============================================================================
echo -e "${GREEN}Optimizing battery settings...${NC}"

# Install battery management GUI
sudo apt install -y gnome-power-manager

# Set battery charge thresholds if supported (helps battery longevity)
# Dell XPS usually supports this through BIOS or smbios
if [ -f /sys/class/power_supply/BAT0/charge_control_start_threshold ]; then
    # Set battery to start charging at 50% and stop at 80% for longevity
    echo 50 | sudo tee /sys/class/power_supply/BAT0/charge_control_start_threshold
    echo 80 | sudo tee /sys/class/power_supply/BAT0/charge_control_end_threshold
    echo -e "${GREEN}Battery charge thresholds configured for longevity${NC}"
fi

# =============================================================================
# WEBCAM SUPPORT
# =============================================================================
# Ensure webcam works properly with latest drivers
echo -e "${GREEN}Installing webcam support...${NC}"
sudo apt install -y v4l-utils guvcview

# =============================================================================
# FINGERPRINT READER (if equipped)
# =============================================================================
# Some XPS 13 9350 models have fingerprint readers
echo -e "${GREEN}Checking for fingerprint reader...${NC}"
if lsusb | grep -i "fingerprint\|biometric" > /dev/null; then
    sudo apt install -y fprintd libpam-fprintd
    echo -e "${GREEN}Fingerprint reader support installed${NC}"
    echo -e "${YELLOW}Run 'fprintd-enroll' to set up fingerprint login${NC}"
else
    echo -e "${YELLOW}No fingerprint reader detected${NC}"
fi

# =============================================================================
# PERFORMANCE MONITORING TOOLS
# =============================================================================
echo -e "${GREEN}Installing performance monitoring tools...${NC}"

# S-tui provides a terminal UI for monitoring temps, frequency, power
sudo apt install -y s-tui stress

# Intel undervolt tool for reducing heat and increasing battery life
# Note: Undervolting may be disabled in BIOS on newer models due to Plundervolt
echo -e "${YELLOW}Attempting to install Intel undervolt tool...${NC}"
sudo apt install -y intel-undervolt 2>/dev/null || {
    echo -e "${YELLOW}Intel undervolt not available - this is normal for newer systems${NC}"
}

# =============================================================================
# APPLY IMMEDIATE OPTIMIZATIONS
# =============================================================================
echo -e "${GREEN}Applying immediate optimizations...${NC}"

# Reload systemd
sudo systemctl daemon-reload

# Apply sysctl changes
sudo sysctl -p

# Restart NetworkManager for WiFi power settings
sudo systemctl restart NetworkManager

# =============================================================================
# COMPLETION
# =============================================================================
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}Dell XPS 13 9350 Setup Complete!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${YELLOW}Optimizations applied:${NC}"
echo "  ✓ Intel graphics drivers and video acceleration"
echo "  ✓ Advanced power management (TLP configured for USB compatibility)"
echo "  ✓ PowerTOP for manual power analysis (auto-tune disabled)"
echo "  ✓ Thermal management to prevent throttling"
echo "  ✓ Touchpad gestures and palm rejection"
echo "  ✓ WiFi 6E and Bluetooth optimization"
echo "  ✓ Audio enhancements for Realtek codec"
echo "  ✓ SSD optimization and TRIM enabled"
echo "  ✓ Firmware update tools (fwupd)"
echo "  ✓ Battery longevity settings"
echo "  ✓ Performance monitoring tools"
echo "  ✓ USB power management disabled (fixes mouse/hub issues)"
echo ""
echo -e "${YELLOW}Recommended actions:${NC}"
echo "  1. Reboot to apply all kernel and driver changes"
echo "  2. Run 'sudo fwupdmgr update' to install firmware updates"
echo "  3. Check 'tlp-stat -b' for battery status and thresholds"
echo "  4. Use 's-tui' to monitor thermals under load"
echo "  5. Run 'sudo powertop' to analyze power usage (manual mode)"
echo ""
echo -e "${BLUE}For manual fan control: sudo i8kfan 1 1 (low) or 2 2 (high)${NC}"
echo -e "${BLUE}For power usage analysis: sudo powertop${NC}"
echo ""
echo -e "${GREEN}Script by Robert Parks for Dell XPS 13 9350 on Ubuntu 24.04.2${NC}"