#!/bin/sh
set -e

pushd "$(dirname $0)" > /dev/null

Install() {
	# Installs current dotfiles onto the system
	#
	echo "[Info] :: Installing dotfiles into $1"

	[[ ! -d "$1" ]] && mkdir -p "$1"

	cp "bashrc"       "$1/.bashrc"
	cp "bash_profile" "$1/.bash_profile"
	cp "bash_aliases" "$1/.bash_aliases"

	mkdir -p "$1/.config"

	cp -r "config/nvim"          "$1/.config"
	cp    "config/starship.toml" "$1/.config"

	sed -i "s/#$HOSTNAME //" "$1/.config/starship.toml"

	# Graphical setups
	#
	case $HOSTNAME in
		kanto|tokyo)
			mkdir -p "$1/.config/sway"
			mkdir -p "$1/.config/swaylock"
			mkdir -p "$1/.config/foot"

			cp    "config/sway/$HOSTNAME.sway" "$1/.config/sway/config"
			cp    "config/swaylock/config"     "$1/.config/swaylock"
			cp    "config/foot/foot.ini"       "$1/.config/foot/foot.ini"
			cp -r "config/rofi"                "$1/.config"

			sed -i "s/#$HOSTNAME //" "$1/.config/foot/foot.ini"

			sed -i "s/\\/\\*$HOSTNAME//" "$1/.config/rofi/theme.rasi"
			sed -i "s/$HOSTNAME\\*\\///" "$1/.config/rofi/theme.rasi"
			;;
	esac
}

Pull() {
	# Allows system changes to be pulled into the repository to be committed
	#
	echo "[Info] :: Pulling dotfile changes from $1"

	cp "$1/.bashrc"       "bashrc"
	cp "$1/.bash_profile" "bash_profile"
	cp "$1/.bash_aliases" "bash_aliases"

	cp -r "$1/.config/nvim"                "config/"
	cp    "$1/.config/starship.toml"       "config/starship.toml"

	case $HOSTNAME in
		kanto|tokyo)
			cp "$1/.config/sway/config"         "config/sway/$HOSTNAME.sway"
			cp "$1/.config/rofi/config.rasi"    "config/rofi/$HOSTNAME.rofi"
			cp "$1/.config/rofi/$HOSTNAME.rasi" "config/rofi/$HOSTNAME.theme"
			cp "$1/.config/swaylock/config"     "config/swaylock"
			cp "$1/.config/foot/foot.ini"       "config/foot/foot.ini"
			;;
	esac
}

INSTALL_DIR=${2:-$HOME}
ACTION=$1

[[ -z $INSTALL_DIR ]] && echo "[Error] :: Installation directory not set" && exit 1

case $ACTION in
	install)
		Install $INSTALL_DIR
		;;
	pull)
		Pull $INSTALL_DIR
		;;
	*)
		echo "usage: $0 <install|pull|diff> [dir]"
		;;
esac

popd > /dev/null
