#!/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"
    ".local/share/gnupg/"
    ".local/share/vpn/"
    "build"
    "downloads"
    "projects"
    "videos"
    "work/opensource"
    "work/projects"
    "work/tools"
)

# Files which should be symlinked in the home folder
LINKED_FILES_HOME=(
    ".config/alacritty"
    ".config/autokey"
    ".config/bat"
    ".config/cmus"
    ".config/compton"
    ".config/cron"
    ".config/custom"
    ".config/dconf"
    ".config/dunst"
    ".config/git"
    ".config/gtk-2.0"
    ".config/gtk-3.0"
    ".config/httpie"
    ".config/i3"
    ".config/maven"
    ".config/mpd"
    ".config/mpv"
    ".config/ncmpcpp"
    ".config/npm"
    ".config/octave"
    ".config/pacman"
    ".config/phpstorm"
    ".config/polybar"
    ".config/python"
    ".config/redshift"
    ".config/sqlite3"
    ".config/streamlink"
    ".config/sxhkd"
    ".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}/.PhpStorm2019.1"]="${XDG_CONFIG_HOME}/phpstorm"
    ["${HOME}/.PhpStorm2019.2"]="${XDG_CONFIG_HOME}/phpstorm"
    ["${HOME}/documents"]="${HOME}/data/Documents"
    ["${HOME}/music"]="${HOME}/data/Media/Music"
    ["${HOME}/pictures"]="${HOME}/data/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=(
    "docker"
    "log"
    "mpd"
    "wheel"
)

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

SYSTEMD_USER_SERVICES=(
    "mpd"
)

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

# npm packages which should be installed globally
NPM_PACKAGES=(
    "@vue/cli"
    "eslint"
    "gatsby-cli"
    "npm-check-updates"
)

# Ruby gems which should be installed
RUBY_GEMS=(
    "docker-sync"
)

# composer packages which should be installed globally
COMPOSER_PACKAGES=(
    "laravel/installer"
)

# Root files which should be copied
declare -A COPY_ROOT_FILES
COPY_ROOT_FILES=(
    ["/etc/docker/daemon.json"]="644"
    ["/etc/gemrc"]="644"
    ["/etc/mkinitcpio.conf"]="644"
    ["/etc/NetworkManager/conf.d/dns.conf"]="644"
    ["/etc/pacman.conf"]="644"
    ["/etc/resolv.conf"]="644"
    ["/etc/sudoers.d/severin"]="0440"
    ["/etc/vconsole.conf"]="644"
    ["/etc/X11/nvidia-xorg.conf.d/00-keyboard.conf"]="644"
    ["/etc/X11/nvidia-xorg.conf.d/20-displaylink.conf"]="644"
    ["/etc/X11/xorg.conf.d/00-keyboard.conf"]="644"
    ["/etc/X11/xorg.conf.d/20-displaylink.conf"]="644"
    ["/etc/zsh/zshenv"]="644"
)


###############################################################################
# Installtion information                                                     #
###############################################################################
echo "${BOLD}Before you continue with this script make sure that:"
echo " • The user severin is added to the sudoers file"
echo " • The multilib repository is uncommented in /etc/pacman.conf"
echo -e " • Your SSH keys are located in ~/.ssh${RESET}"

read -p "Are you ready to continue? (y/n): " -n 1 -r
echo ""

if [[ $REPLY =~ ^[nN]$ ]]
then
    exit
fi

###############################################################################
# Work specific settings                                                      #
###############################################################################
if [ "${IS_WORK}" = "1" ]; then
    export GIT_SSH_COMMAND="ssh -i /home/severin/.ssh/severin_id_rsa"
fi


###############################################################################
# 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 default 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"

#yay -Rsu $(comm -23 <(pacman -Qq | sort) <(cat "${PACKAGES_DIR}/packages.native.list" "${PACKAGES_DIR}/packages.aur.list" | sort))

print_section "Installing global npm packages"
print_log "Installing ${#NPM_PACKAGES[@]} packages"
npm i -g "${NPM_PACKAGES[@]}"

print_section "Installing global composer packages"
print_log "Installing ${#COMPOSER_PACKAGES[@]} packages"
composer global require "${COMPOSER_PACKAGES[@]}"

print_section "Installing ruby gems"
print_log "Installing ${#RUBY_GEMS[@]} packages"
gem install "${RUBY_GEMS[@]}"

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

for dir in "${DIRECTORIES[@]}"
do
    print_log "Creating directory ${YELLOW}${HOME}/${dir}${RESET}"
    mkdir -p "${HOME}/${dir}"
done


###############################################################################
# Prepare work tools                                                          #
###############################################################################
print_section "Prepare work tools"
print_log "Installing dde"
if [ ! -d "${HOME}/work/tools/dde" ]; then 
    git clone "https://github.com/whatwedo/dde" "${HOME}/work/tools/dde"
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

for service in "${SYSTEMD_USER_SERVICES[@]}"
do
    print_log "Enabling service ${YELLOW}${service}${RESET}"
    systemctl --user 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 root files                                                          #
###############################################################################
print_section "Copying root files"
for file in "${!COPY_ROOT_FILES[@]}"; do
    print_log "Copying ${YELLOW}${file}${RESET}"
    sudo install -Dm "${COPY_ROOT_FILES[${file}]}" "${SYSTEM_DIR}${file}" "${file}"
done


###############################################################################
# Enable ntp                                                                  #
###############################################################################
print_section "Enabling ntp"
sudo timedatectl set-ntp true


###############################################################################
# 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"

###############################################################################
# Fonts                                                                       #
###############################################################################
print_section "Fonts"
sudo mkfontdir /usr/share/fonts/75dpi
sudo mkfontdir /usr/share/fonts/100dpi
print_log "Prepare xorg fonts"

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

###############################################################################
# Post installation information                                               #
###############################################################################
print_section "Post installation information"
echo "${BOLD}Make sure you do the following after this installation:"
echo -e " • Run ${YELLOW}~/.config/polybar/scripts/gmail/auth.py${RESET}${BOLD}"
echo " • Download settings for Visual Studio Code"