#!/bin/sh

CONFIGFILES_REPOSITORY="https://git.pew.io/technowitch/elas-arch-config.git"
CONFIGFILES_DIRECTORY="~/dotfiles"

# This script installs these dotfiles.

set -e -u

printf '\e[1mInstalling dotfiles\e[0m\n'

case "$(uname)" in

'Linux')
	if [ ! -x "$(command -v pacman)" ]; then
		printf '\e[1mArch Linux is the only distro currently supported for automated setup\e[0m\n'
		exit 1
	fi

	# Install Git if not installed
	if [ ! -x "$(command -v git)" ]; then
		printf '\e[1mInstalling Git\e[0m\n'
		sudo pacman -S --noconfirm --needed git
	fi

	# git clone these dotfiles if not done yet
	if [ ! -d "$CONFIGFILES_DIRECTORY" ]; then
		printf '\e[1mCloning dotfiles repo\e[0m\n'
		git clone "$CONFIGFILES_REPOSITORY" "$CONFIGFILES_DIRECTORY"
	fi

	# Install Stow if not installed
	sudo pacman -S --noconfirm --needed stow
	
	
	# Stow subdirectories of dotfiles
	printf '\e[1mLinking dotfiles to your home directory\e[0m\n'
	for dir in "$CONFIGFILES_DIRECTORY"/*/; do
		stow --dir "$CONFIGFILES_DIRECTORY" --target "$HOME" "$(basename "${dir}")"
	done

	# Install Paru if not installed
	if [ ! -x "$(command -v paru)" ]; then
		printf '\e[1mInstalling Paru\e[0m\n'
		git clone https://aur.archlinux.org/paru-bin.git /tmp/paru
		(cd /tmp/paru && makepkg -si)
	fi

	# Set colors for pacman
	sudo sed -i 's/#Color/Color/' /etc/pacman.conf
	printf "\n\nILoveCandy\n" | sudo tee -a /etc/pacman.conf >/dev/null
	# sudo sed -i 's/#Color/Color/' /etc/pacman.conf

	# Install Pacmanfile if not installed
	if [ ! -x "$(command -v pacmanfile)" ]; then
		printf '\e[1mInstalling Pacmanfile\e[0m\n'
		paru -S --noconfirm --needed pacmanfile
	fi

	# Install packages using Pacmanfile
	printf '\e[1mInstalling desired packages using Pacmanfile\e[0m\n'
	pacmanfile sync --noconfirm

	# Change npm folder
	if [ -x "$(command -v npm)" ]; then
		npm set prefix="$HOME/.local"
	fi
	;;

# Default
*)
	printf '\e[1mOS not supported for automated setup. Please install manually.\e[0m\n'
	exit 1
	;;
esac

# Install prezto
if [ ! -d ~/.zprezto ]; then
	git clone --recursive https://github.com/sorin-ionescu/prezto.git "${ZDOTDIR:-$HOME}/.zprezto"
fi

# Use zsh
if [ -x "$(command -v zsh)" ] && [ "$SHELL" != "$(command -v zsh)" ]; then
	chsh -s "$(command -v zsh)"
fi

# Run full system upgrade
. "$CONFIGFILES_DIRECTORY/zsh/.zsh.d/functions.zsh"
EDITOR=nvim pacu

printf '\e[1mYour config is successfully installed. Please reboot to finalize.\e[0m\n'
