#!/bin/sh

LIGHT_THEME="rose-pine"
DARK_THEME="nord"
KITTY_LIGHT_THEME="Rosé Pine Dawn"
NVIM_COLORSCHEME_LINE=41

capitalize() {
	printf '%s' "$1" | head -c 1 | tr "[:lower:]" "[:upper:]"
	printf '%s' "$1" | tail -c '+2' | tr "-" " " | tr "e" "é"
}

change_theme() {
	sed -e "$NVIM_COLORSCHEME_LINE s/$1/$2/" -i ~/.config/nvim/init.vim
	sed -i "s/$1/$2/" ~/.config/zathura/zathurarc
	if [ "$2" = "$LIGHT_THEME" ]; then
		kitty +kitten themes --reload-in=all "$KITTY_LIGHT_THEME"
	else
		kitty +kitten themes --reload-in=all "$(capitalize "$2")"
	fi
	nvr --remote-send ":source ~/.config/nvim/init.vim <CR>"
}

recolor_zathura() {
	instances=$(pgrep -f zathura)
	temp_file=/tmp/zathura-instances
	echo "$instances" >"$temp_file"
	while IFS= read -r line; do
		dbus-send --type="method_call" --dest=org.pwmt.zathura.PID-"$line" \
			/org/pwmt/zathura org.pwmt.zathura.ExecuteCommand string:"source"
	done <"$temp_file"
}

if [ $# -lt 1 ]; then
	echo "Usage: switch_theme <mode>"
	echo "mode: dark|light"
	exit 1
fi

mode=$1

if [ "$mode" = "light" ]; then
	emacsclient --eval "(load-theme 'os1 'no-confirm)"
	change_theme "$DARK_THEME" "$LIGHT_THEME"
	recolor_zathura
else
	emacsclient --eval "(load-theme 'doom-one 'no-confirm)"
	change_theme "$LIGHT_THEME" "$DARK_THEME"
	recolor_zathura
fi
