#!/usr/bin/env bash
# 
# SCRIPT NAME:
# install
#
# AUTHOR:
# Severin Kaderli <severin@kaderli.dev>
#
# DESCRIPTION:
# This is the main installation script for my dotfiles. It setups the symlinks
# to the neeeded files, creates new directories, enables systemd services,
# installs pacman packages and gives out the correct permissions to files.
#
# USAGE:
# ./install
. ./system/.config/custom/env
. ./system/.local/bin/utils

###############################################################################
# Configuration variables                                                     #
###############################################################################
set -e

HOST="$(hostname)"

# Directories which should be created
DIRECTORIES=(
    ".local/log"
    "build"
    "documents"
    "downloads"
    ".local/keys"
    "music"
    "pictures"
    "projects"
    "videos"
    ".local/share/gnupg/"
)

WORK_DIRECTORIES=(
    "work"
    ".local/log"
    "downloads"
    ".local/keys"
    ".local/share/gnupg/"
)

# Files which should be symlinked in the home folder
LINKED_FILES_HOME=(
    ".config/alacritty"
    ".config/autokey"
    ".config/bat"
    ".config/cmus"
    ".config/sxhkd"
    ".config/compton"
    ".config/cron"
    ".config/custom"
    ".config/dconf"
    ".config/dunst"
    ".config/git"
    ".config/gtk-2.0"
    ".config/gtk-3.0"
    ".config/httpie"
    ".config/maven"
    ".config/octave"
    ".config/i3"
    ".config/mpv"
    ".config/newsboat"
    ".config/npm"
    ".config/pacman"
    ".config/polybar"
    ".config/python"
    ".config/redshift"
    ".config/sqlite3"
    ".config/streamlink"
    ".config/task"
    ".config/Trolltech.conf"
    ".config/user-dirs.dirs"
    ".config/user-dirs.locale"
    ".config/vim"
    ".config/vue"
    ".config/wget"
    ".config/X11"
    ".config/zathura"
    ".config/zsh"
    ".local/bin"
    ".local/share/gnupg/gpg-agent.conf"
)

# Symlinks which will be created
declare -A LINKED_FILES
LINKED_FILES=(
    ["${HOME}/music"]="${HOME}/documents/Media/Music"
    ["${HOME}/pictures"]="${HOME}/documents/Media/Pictures"
)

# Permissions to set for folders and files
declare -A PERMISSIONS
PERMISSIONS=(
    ["${XDG_BIN_HOME}"]="744"
)

# Groups the user should be added to
ADD_GROUPS=(
    "log"
    "wheel"
)

# Array of systemd services which should be enabled
SYSTEMD_SERVICES=(
    "cronie"
    "NetworkManager"
    "org.cups.cupsd"
    "suspend"
    "xboxdrv"
)

# Rust components which should be installed
RUST_COMPONENTS=(
    "rls"
    "rustfmt"
)

###############################################################################
# Install package manager and packages                                        #
###############################################################################
print_section "Installing package requirements"
sudo pacman -S sudo ccache git base-devel --noconfirm --needed

print_section "Installing yay"
is_yay_installed=$(command -v yay)

# Install yay if not already installed
if [ -z "${is_yay_installed}" ]; then
    git clone https://aur.archlinux.org/yay.git
    (
    cd yay || exit
    makepkg -si --noconfirm --skippgpcheck
    )
    rm -rf yay
else
    print_log "yay is already installed"
fi

print_section "Installing native packages"
# List created using: yay -Qqen > packages.native.list
package_count=$(< "${PACKAGES_DIR}/packages.native.list" wc -l)
print_log "Installing ${package_count} packages"
yay -Syy > /dev/null 2>&1
yay -S --noconfirm --sudoloop --needed --devel --nopgpfetch --mflags --skippgpcheck - < "${PACKAGES_DIR}/packages.native.list"

print_section "Installing Rust toolchain and components"
rustup toolchain install beta
rustup component add "${RUST_COMPONENTS[@]}"
rustup default beta

print_section "Installing AUR packages"
package_count=$(< "${PACKAGES_DIR}/packages.aur.list" wc -l)
# List created using: yay -Qqem > packages.aur.list
print_log "Installing ${package_count} packages"
yay -Syy > /dev/null 2>&1
yay -S --noconfirm --sudoloop --needed --devel --nopgpfetch --mflags --skippgpcheck - < "${PACKAGES_DIR}/packages.aur.list"


###############################################################################
# Creating directories                                                        #
###############################################################################
print_section "Creating directories"


if [ "${IS_WORK}" = "1" ]; then
    for dir in "${WORK_DIRECTORIES[@]}"
    do
        print_log "Creating directory ${YELLOW}${HOME}/${dir}${RESET}"
        mkdir -p "${HOME}/${dir}"
    done
else
    for dir in "${DIRECTORIES[@]}"
    do
        print_log "Creating directory ${YELLOW}${HOME}/${dir}${RESET}"
        mkdir -p "${HOME}/${dir}"
    done
fi

###############################################################################
# Creating symlinks                                                           #
###############################################################################
print_section "Creating symlinks"
for file in "${LINKED_FILES_HOME[@]}";
do
    print_log "Linking ${YELLOW}${HOME}/${file}${RESET} to ${YELLOW}${SYSTEM_DIR}/${file}${RESET}"
    rm -rf "${HOME:?}/${file}"
    ln -fs "${SYSTEM_DIR}/${file}" "${HOME}/${file}"
done


for file in "${!LINKED_FILES[@]}"; do
    print_log "Linking ${YELLOW}${file}${RESET} to ${YELLOW}${LINKED_FILES[${file}]}${RESET}"
    rm -rf "${file}"
    ln -fs "${LINKED_FILES[${file}]}" "${file}"
done


###############################################################################
# Giving permissions                                                          #
###############################################################################
print_section "Giving permissions"
for permission in "${!PERMISSIONS[@]}"; do
    print_log "Changing owner of ${YELLOW}${permission}${RESET} to ${YELLOW}${USER}${RESET}"
    sudo chown -R "${USER}" "${permission}"
    print_log "Changing permission of ${YELLOW}${permission}${RESET} to ${YELLOW}${PERMISSIONS[${permission}]}${RESET}"
    sudo chmod -R "${PERMISSIONS[${permission}]}" "${permission}"
done


###############################################################################
# Adding user to groups                                                       #
###############################################################################
print_section "Adding user to groups"
for group in "${ADD_GROUPS[@]}"
do
    print_log "Adding user ${YELLOW}${USER}${RESET} to group ${YELLOW}${group}${RESET}"
    sudo gpasswd -a "${USER}" "${group}" > /dev/null 2>&1
done


###############################################################################
# Copying systemd services                                                    #
###############################################################################
print_section "Copying systemd services"
for file in "${SYSTEM_DIR}/etc/systemd/system/"*
do
    print_log "Copying ${YELLOW}$(basename "${file}")${RESET} to ${YELLOW}/etc/systemd/system${RESET}"
    sudo install -m 644 "${file}" "/etc/systemd/system"
done


###############################################################################
# Enabling systemd services                                                   #
###############################################################################
print_section "Enabling systemd services"
for service in "${SYSTEMD_SERVICES[@]}"
do
    print_log "Enabling service ${YELLOW}${service}${RESET}"
    sudo systemctl enable "${service}"
done


###############################################################################
# Enabling systemd services                                                   #
###############################################################################
print_section "Copying custom udev rules"
for file in "${SYSTEM_DIR}/etc/udev/rules.d/"*.rules
do
    print_log "Copying ${YELLOW}$(basename "${file}")${RESET} to ${YELLOW}/etc/udev/rules.d/${RESET}"
    sudo cp "${file}" "/etc/udev/rules.d/"
done
sudo udevadm control --reload-rules


###############################################################################
# Copying other files                                                         #
###############################################################################
print_section "Copying other files"

print_log "Copying custom sudoers file to ${YELLOW}/etc/sudoers.d${RESET}"
sudo install -m 0440 "${SYSTEM_DIR}/etc/sudoers.d/severin" "/etc/sudoers.d"

print_log "Copying docker configuration to ${YELLOW}/etc/docker${RESET}"
sudo install -m 644 "${SYSTEM_DIR}/etc/docker/daemon.json" "/etc/docker"

print_log "Copying zshenv to ${YELLOW}/etc/zsh${RESET}"
sudo install -m 644 "${SYSTEM_DIR}/etc/zsh/zshenv" "/etc/zsh"

###############################################################################
# Setting lockscreen image                                                    #
###############################################################################
print_section "Setting lockscreen image"
betterlockscreen -u "${DOTFILES}/assets/lockscreen.${HOST}.jpg" > /dev/null 2>&1
print_log "Lockscreen generated"

###############################################################################
# Creating issue file                                                         #
###############################################################################
print_section "Creating issue file"
{
    echo '\e{red}';
    < "/etc/hostname" tr '[:lower:]' '[:upper:]' | figlet -f big | sed "s/\\\\/\\\\\\\/g";
    echo -e "\\\r (\\\l)";
    echo '\e{reset}';
} > "/tmp/issue"
sudo install "/tmp/issue" "/etc/issue"
print_log "Issue file created"

###############################################################################
# Set default shell                                                           #
###############################################################################
print_section "Set default shell"
chsh -s "/bin/zsh"
print_log "Set default shell to zsh"