#!/bin/sh

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

printf "%bChanging directory to %s %b\n" "$BLUE" "$dotfiles" "$NC"
if ! cd "$dotfiles"; then
	printf "%bCould not CD into %s%b\n" "$RED" "$dotfiles" "$NC"
	exit
fi
printf "\n"

printf "%bStashing existing changes...%b\n" "$BLUE" "$NC"
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 "%bPulling updates from dotfiles repo...%b\n" "$BLUE" "$NC"
git pull origin main
git submodule update --remote --recursive --init
printf "\n"

if [ $needs_pop -eq 1 ]; then
	printf "%bPopping stashed changes...%b\n" "$BLUE" "$NC"
	git stash pop
fi
printf "\n"

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

printf "%bGenerating librewolf profiles...%b\n" "$BLUE" "$NC"
"$dotfiles"/.librewolf/generate.sh
printf "\n"

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

printf "%bDotfiles Synced Successfully!%b\n" "$GREEN" "$NC"