#!/bin/sh
set -e

# === Colors ===
RED="\033[1;31m"
GREEN="\033[1;32m"
YELLOW="\033[1;33m"
BLUE="\033[1;34m"
MAGENTA="\033[1;35m"
CYAN="\033[1;36m"
RESET="\033[0m"

log_info() { printf "${CYAN}[*]${RESET} %s\n" "$1"; }
log_success() { printf "${GREEN}[✓]${RESET} %s\n" "$1"; }
log_warn() { printf "${YELLOW}[!]${RESET} %s\n" "$1"; }
log_error() { printf "${RED}[✗]${RESET} %s\n" "$1"; }

ORIG_PWD=$(pwd)
ORIG_USER=$(logname)
ORIG_HOME=$(getent passwd "$ORIG_USER" | cut -d: -f6)

# === Elevate to root if needed ===
if [ "$(id -u)" -ne 0 ]; then
	exec sudo "$0" "$@"
fi

# === Package Groups ===
ESSENTIAL_PACKAGES="
    base-devel 
    python3 
"

SYSTEM_TOOLS="
    man
    vim 
    neovim 
    nnn 
    btop 
"

DISPLAY_MANAGER="
    ly 
    qt5-graphicaleffects
    qt5ct
    qt6ct
    weston
"

WAYLAND_ENVIRONMENT="
    hyprland 
    hyprpaper
    hyprlock
    waybar 
    kitty 
    rofi 
    mako 
    libnotify 
    brightnessctl
    grim 
    slurp
    wl-clipboard 
    wl-clip-persist 
    wayland-utils 
    xorg-xwayland 
    xdg-desktop-portal-hyprland 
    hyprpolkitagent
    thunar
"

AUDIO_PACKAGES="
    pipewire 
    pipewire-pulse 
    wireplumber 
    pavucontrol
"

FONTS_AND_THEME="
    otf-font-awesome 
    noto-fonts 
    noto-fonts-cjk 
    ttf-jetbrains-mono 
    orchis-theme
"

NETWORK_AND_APPS="
    firefox
"

MEDIA_PACKAGES="
    mpv 
    mpv-mpris 
    eog 
    lollypop 
    ffmpeg
"

# === Functions ===
update_system() {
	log_info "Updating system..."
	pacman -Syu --noconfirm
}

install_packages() {
	log_info "Installing packages..."
	pacman -Sy --noconfirm --needed \
		$ESSENTIAL_PACKAGES \
		$SYSTEM_TOOLS \
		$DISPLAY_MANAGER \
		$WAYLAND_ENVIRONMENT \
		$AUDIO_PACKAGES \
		$FONTS_AND_THEME \
		$NETWORK_AND_APPS \
		$MEDIA_PACKAGES
}

install_nvidia_drivers() {
	log_info "Checking for NVIDIA GPU..."

	if lspci | grep -i 'vga\|3d' | grep -iq 'nvidia'; then
		log_success "NVIDIA GPU detected."

		log_info "Installing NVIDIA drivers..."
		pacman -Sy --noconfirm --needed nvidia-open nvidia-utils

		log_info "Running mkinitcpio..."
		mkinitcpio -P

		log_info "Enabling NVIDIA modeset..."
		mkdir -p /etc/modprobe.d
		echo "options nvidia_drm modeset=1" >/etc/modprobe.d/nvidia.conf

	else
		log_info "No NVIDIA GPU detected. Skipping NVIDIA driver installation."
	fi
}

install_system_files() {
	log_info "Installing system files from ./system_files to /..."

	if [ -d "system_files" ]; then
		cp -a ./system_files/. /

		chown root:root /
		chown root:root /etc
		chown root:root /usr
		chown root:root /var
		chown root:root /run

		log_success "System files copied to root (/)."
	else
		log_warn "'system_files' directory not found."
	fi
}

apply_gtk_settings() {
	log_info "Applying GTK settings..."
	export XDG_RUNTIME_DIR="/run/user/$(id -u "$ORIG_USER")"
	DBUS_ADDR="unix:path=${XDG_RUNTIME_DIR}/bus"

	for setting in \
		"org.gnome.desktop.interface gtk-theme Graphite-Dark-compact" \
		"org.gnome.desktop.interface icon-theme Tela-grey-dark" \
		"org.gnome.desktop.interface color-scheme prefer-dark"; do
		if sudo -u "$ORIG_USER" \
			DBUS_SESSION_BUS_ADDRESS="$DBUS_ADDR" \
			gsettings set $setting; then
			log_success "Set $setting"
		else
			log_warn "Failed to set $setting"
		fi
	done
}

enable_ly() {
	log_info "Enabling Ly..."
	systemctl enable ly@tty2.service
}

install_gtk_theme() {
	log_info "Installing GTK theme..."

	if [ -d "$ORIG_HOME/.themes/Graphite-Dark-compact" ]; then
		log_success "GTK theme already installed."
		return
	fi

	sudo -u "$ORIG_USER" mkdir -p "$ORIG_HOME/Repositories"
	cd "$ORIG_HOME/Repositories" || return

	if [ ! -d "graphite-gtk" ]; then
		sudo -u "$ORIG_USER" git clone https://github.com/vinceliuice/Graphite-gtk-theme.git graphite-gtk
	else
		log_warn "Theme repo already exists, skipping clone."
	fi

	cd "$ORIG_HOME/Repositories/graphite-gtk" || return
	sudo -u "$ORIG_USER" ./install.sh -c dark --tweaks rimless --size compact --round 0px

	log_info "Cleaning up theme repository..."
	rm -rf "$ORIG_HOME/Repositories/graphite-gtk"
	log_success "GTK theme installed and repo removed."
}

install_gtk_icons() {
	log_info "Installing Tela icons..."

	if [ -d "$ORIG_HOME/.local/share/icons/Tela-grey-dark" ]; then
		log_success "GTK theme already installed."
		return
	fi

	sudo -u "$ORIG_USER" mkdir -p "$ORIG_HOME/Repositories"
	cd "$ORIG_HOME/Repositories" || return

	if [ ! -d "tela-icons" ]; then
		sudo -u "$ORIG_USER" git clone https://github.com/vinceliuice/Tela-icon-theme.git tela-icons
	else
		log_warn "Theme repo already exists, skipping clone."
	fi

	cd "$ORIG_HOME/Repositories/tela-icons" || return
	sudo -u "$ORIG_USER" ./install.sh -c grey

	log_info "Cleaning up icons repository..."
	rm -rf "$ORIG_HOME/Repositories/tela-icons"
	log_success "Tela icons installed and repo removed."
}

run_dotfiles_setup() {
	log_info "Running dotfiles setup..."
	cd "$ORIG_PWD"

	sudo -u "$ORIG_USER" mkdir -p \
		"$ORIG_HOME/Downloads" \
		"$ORIG_HOME/Documents" \
		"$ORIG_HOME/Pictures" \
		"$ORIG_HOME/Videos" \
		"$ORIG_HOME/Repositories"

	if [ -d "home" ]; then
		log_info "Copying files from ./home to $ORIG_HOME..."

		cp -a ./home/. "$ORIG_HOME/"

		chown -R "$ORIG_USER:$ORIG_USER" "$ORIG_HOME"

		log_info "Select monitor configuration:"
		echo "1) monitors-1.conf"
		echo "2) monitors-2.conf"
		printf "${MAGENTA}Enter your choice (1 or 2): ${RESET}"
		read -r MONITOR_CHOICE

		MONITORS_DIR="$ORIG_HOME/.config/hypr"
		case "$MONITOR_CHOICE" in
		1)
			cp "$MONITORS_DIR/monitors-1.conf" "$MONITORS_DIR/monitors.conf"
			;;
		2)
			cp "$MONITORS_DIR/monitors-2.conf" "$MONITORS_DIR/monitors.conf"
			;;
		*)
			log_warn "Invalid choice. Skipping monitor config setup."
			;;
		esac

		chown "$ORIG_USER:$ORIG_USER" "$MONITORS_DIR/monitors.conf" 2>/dev/null || true
		log_success "Monitor config set to monitors.conf"

		log_success "Files copied to user home directory."
	else
		log_warn "'home' directory not found in script directory."
	fi
}

# === Main flow ===
update_system
install_packages
install_nvidia_drivers
install_gtk_theme
install_gtk_icons
apply_gtk_settings
install_system_files
run_dotfiles_setup
enable_ly

log_success "Setup completed successfully."
