#!/bin/bash
# purpose: Setup script for my Hyprland desktop with ready to use

set -e

# Color definitions for output formatting
WHITE='\033[0;37m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
RED='\033[0;31m'

RESET='\033[0m'

# Function to print colored messages
print_message() {
    local color=$1
    local message=$2
    local options=${3:-""}  # Default to empty if no options provided
    echo -e ${options} "${color}${message}${RESET}"
}

guard_pass() {
    # check if pacman exists
    if ! command -v pacman &> /dev/null; then
        print_message "${RED}" "This script is designed for Arch Linux and requires pacman."
        exit 1
    fi

    # check user
    # this script should not be run as root but the user running it needs to have sudo privileges
    if [[ $EUID -eq 0 ]]; then
        print_message "${RED}" "This script should not be run as root!"
        exit 1
    fi

    # check if the user has sudo privileges
    sudo -i true 2>/dev/null || {
        print_message "${RED}" "You don't have sudo privileges. Please run this script with a user that has sudo access."
            exit 1
        }
}

ensure_yay() {
    if command -v yay &> /dev/null; then
        return
    fi
    # then install yay
    print_message "${YELLOW}" "Yay is not installed. Installing yay..."
    print_message "${WHITE} " "Installing yay dependencies..."

    # install the dependencies to install yay
    sudo pacman -Sy --noconfirm --needed git wget base-devel

    print_message "${WHITE}" "Cloning yay repository..."
    git clone https://aur.archlinux.org/yay.git /tmp/yay

    print_message "${WHITE}" "Building and installing yay..."
    cd /tmp/yay
    makepkg -si --noconfirm
}

install_packages() {
    # in this function we'll install packages that will resemble my desktop environment
    print_message ${YELLOW} "Installing dependencies..."
    print_message ${RED} "This may take a while..."
    # sleep 5
    yay -Syyu --noconfirm --needed hyprland hyprpaper hyprlock hyprcursor xdg-desktop-portal-hyprland xdg-desktop-portal-gtk polkit wofi waybar greetd greetd-regreet kitty uwsm papirus-icon-theme swaync xorg-xhost polkit-gnome nemo nemo-fileroller brightnessctl playerctl pipewire pipewire-pulse pipewire-alsa wireplumber nwg-look otf-font-awesome ttf-font-awesome ttf-nerd-fonts-symbols ttf-fira-code ttf-input ttf-liberation ttf-ubuntu-font-family ttf-dejavu noto-fonts nerd-fonts pavucontrol wl-clipboard eog grim slurp hyprpicker jq gnome-text-editor npm nodejs tesseract tesseract-data-eng wlogout bettergruvbox-gtk-theme papirus-folders bibata-cursor-theme-bin grimblast-git zen-browser-bin bemoji wtype zsh fzf ranger tmux zoxide obsidian tree-sitter-cli imagemagick lazygit network-manager-applet
}

set_nopasswd() {
    # set sudo to not require a password
    print_message "${YELLOW}" "Setting sudo to not require a password for the sake of this installation..."
    echo "${USER} ALL=(ALL) NOPASSWD: ALL" | sudo tee /etc/sudoers.d/nopasswd > /dev/null
}

rm_nopasswd() {
    # remove the nopasswd file
    print_message "${GREEN}" "Removing the nopasswd file..."
    sudo rm /etc/sudoers.d/nopasswd
}

setup_oh_my_zsh() {
    # install oh-my-zsh
    if [[ ! -d "${HOME}/.oh-my-zsh" ]]; then
        print_message "${YELLOW}" "Installing Oh My Zsh..."
        sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)" "" --unattended
    else
        print_message "${GREEN}" "Oh My Zsh is already installed."
    fi
    # set zsh as the default shell
    if [[ "$SHELL" != "/bin/zsh" ]]; then
        print_message "${YELLOW}" "Setting Zsh as the default shell..."
        sudo chsh -s /bin/zsh ${USER}
    else
        print_message "${GREEN}" "Zsh is already the default shell."
    fi
    # install zsh plugins
    if [[ ! -d "${HOME}/.oh-my-zsh/custom/plugins/zsh-autosuggestions" ]]; then
        print_message "${YELLOW}" "Installing zsh-autosuggestions plugin..."
        git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions
    fi
    if [[ ! -d "${HOME}/.oh-my-zsh/custom/plugins/zsh-syntax-highlighting" ]]; then
        print_message "${YELLOW}" "Installing zsh-syntax-highlighting plugin..."
        git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting
    fi
}

place_dotfiles() {
    # place the dotfiles in the home directory

    if [ -d /tmp/dotfiles ]; then
        print_message "${YELLOW}" "Removing old dotfiles directory..."
        rm -rf /tmp/dotfiles
    fi

    print_message "${YELLOW}" "Cloning dotfiles repository..."
    git clone --depth=1 https://git.flouda.net/flouda/dotfiles-old.git /tmp/dotfiles
    cd /tmp/dotfiles
    
    print_message "${WHITE}" "Copying dotfiles to their places..."
    sudo cp greetd/* /etc/greetd/
    if [[ ! -d /usr/share/backgrounds ]]; then
        sudo mkdir /usr/share/backgrounds/
    fi
    sudo cp wp.png /usr/share/backgrounds/

    cp wp.png ~/
    cp -r user-home/.* ~/

    cp user-home/aliases.zsh ${HOME}/.oh-my-zsh/custom/aliases.zsh 
    cp user-home/functions.zsh ${HOME}/.oh-my-zsh/custom/functions.zsh 
    cp user-home/hooks.zsh ${HOME}/.oh-my-zsh/custom/hooks.zsh 
    cp user-home/environment.zsh ${HOME}/.oh-my-zsh/custom/environment.zsh 
}

foss_setup() {
    # foss: First-time login, One-shot, Self-destroying Setup
    print_message "${YELLOW}" "Setting up FOSS (First-time login, One-shot, Self-destroying Setup)..."
    wget https://git.flouda.net/flouda/snippets/raw/branch/main/4871244/foss-setup.sh -O ${HOME}/.config/foss-setup.sh
    wget https://git.flouda.net/flouda/snippets/raw/branch/main/4871244/foss.service -O ${HOME}/.config/systemd/user/foss.service

    chmod +x ~/.config/foss-setup.sh

    # enable the foss service
    touch ${HOME}/first-run

    systemctl --user daemon-reexec
    systemctl --user daemon-reload
    systemctl --user enable foss.service
}

reboot_prompt() {
    # display a reboot in 5 seconds prompt
    print_message "${RED}" "Your system will reboot in 5 seconds."

    # start reboot in 5 seconds command in the background
    sudo sh -c 'sleep 5 && systemctl reboot --no-wall' &
    
    # remove the nopasswd file
    rm_nopasswd

    # countdown for reboot
    for i in {5..1}; do
        echo -ne "${YELLOW}Rebooting in ${i} seconds...\r"
        sleep 1
    done

    echo -e "\n${RED}Rebooting now...${RESET}"

    # reboot the system
    wait
}

guard_pass

# after setting nopasswd even when a crash happens we need to remove it
set_nopasswd
trap 'rm_nopasswd' EXIT

# first upgrade the system
sudo pacman -Syyu --noconfirm --needed

ensure_yay
install_packages
setup_oh_my_zsh
place_dotfiles

# thank you for using my setup script
echo -e "${GREEN}Setup script completed successfully!${RESET}"

# start greetd service
sudo systemctl enable greetd.service

foss_setup

reboot_prompt

wait
