#!/bin/sh

GREEN='\033[1;32m'
BLUE='\033[1;34m'
RED='\033[1;30m'
NC='\033[0m'
dotfiles="${1:-$HOME/.dotfiles}"

printf "${BLUE}Changing directory to $dotfiles${NC}\n"
if ! cd "$dotfiles"; then
	printf "${RED}Could not CD into $dotfiles${NC}\n"
	exit
fi
printf "\n"

printf "${BLUE}Stashing existing changes...${NC}\n"
stash_result=$(git stash push -m "sync-dotfiles: Before syncing dotfiles")
needs_pop=1
if [ "$stash_result" = "No local changes to save" ]; then
	needs_pop=0
fi
printf "\n"

printf "${BLUE}Pulling updates from dotfiles repo...${NC}\n"
git pull origin main
git submodule update --remote --recursive --init
printf "\n"

if [ $needs_pop -eq 1 ]; then
	printf "${BLUE}Popping stashed changes...${NC}\n"
	git stash pop
fi
printf "\n"

unmerged_files=$(git diff --name-only --diff-filter=U)
if [ -n "$unmerged_files" ]; then
	printf "${RED}The following files have merge conflicts after popping the stash:${NC}\n"
	printf "\n"
	printf %"s\n" "$unmerged_files\n"
else
	stow -t "$HOME" . || printf "${RED}Stow uninstalled or not in path!${NC}\n"
fi

printf "${BLUE}Generating librewolf profiles...${NC}\n"
$dotfiles/.librewolf/generate.sh
printf "\n"

printf "Recompile/Install src files? [y/N] \n"
read ans
[ $ans = "y" ] && for f in $dotfiles/.local/src/*; do
	if ! cd "$f"; then
		printf "${RED}Could not CD into $f${NC}\n"
		exit
	fi
	sudo make install
done

printf "${GREEN}Dotfiles Synced Successfully!${NC}\n"