#!/usr/bin/env fish

# This script's purpose is to setup the dotfiles configuration for an existing
# and provisioned machine. For provisioning, see `./dotfiles-init`.

set dfp (realpath (dirname (status -f))/../..)
set lock_file $HOME/.using-lytedev-dotfiles.lock

if not test -f $lock_file
	echo "This will delete existing files. Make sure you know what you're doing."
	echo 'Are you sure you want to continue? [y/N]'
	read response
	set response (string lower $response)
	if string match $response y
		echo "agreed" > "$lock_file"
	else
		exit 1
	end
end

set -q XDG_CONFIG_HOME || set XDG_CONFIG_HOME $HOME/.config
set h $HOME; set c $XDG_CONFIG_HOME
if test -d $c/lytedev-env
	echo "Warning: no environment-specific configuration detected!"
end

function l -a dot -a target -d "Symlink a dotfile configuration file or directory"
	if test -L $target || test -f $target || test -d $target
		rm -rf "$target"
	end
	# check if the directory that will contain the link exists
	set -l d (dirname $target)
	test -d $d || mkdir -p $d
	ln -s (pwd)/$dot $target
	echo Linked $dot to $target
end

pushd $dfp
l common/tmux/conf $h/.tmux.conf
test -d ~/.tmux/pluginx/tpm || \
	git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm
l common/zellij $c/zellij
l common/fish $c/fish
l common/bat $c/bat
l common/bash/rc $h/.bashrc
l common/wezterm $c/wezterm
l common/kitty $c/kitty
l common/weechat $h/.weechat
l common/scim/rc $h/.scimrc
l common/scim/lua $h/.scim/lua
l common/nnn $c/nnn
l common/kak $c/kak
l common/helix $c/helix
l common/gitui $c/gitui
l common/gpg/agent.conf $h/.gnupg/gpg-agent.conf
chmod og-rwx ~/.gnupg
l common/htop/rc $c/htop/htoprc
l common/kitty $c/kitty
l common/alacritty $c/alacritty
l common/pgcli $c/pgcli
l common/mutt/rc $h/.muttrc
l common/git/config $h/.gitconfig
l common/elixir/iex.exs $h/.iex.exs
l common/blender/userpref.blend $c/blender/2.93/config/userpref.blend
l common/lemonade/config.toml $c/lemonade.toml
l common/tig/rc $h/.tigrc
popd

for s in $c/lytedev-env/*/dotfiles-setup.d.fish
	source $s $dfp $h $c
end

set -q ENV_PATH || set ENV_PATH $XDG_CONFIG_HOME/lytedev-env
set -q DOTFILES_PATH || set DOTFILES_PATH $XDG_CONFIG_HOME/lytedev-dotfiles
rm -f $ENV_PATH/empty
ln -s $DOTFILES_PATH/common/empty-env $ENV_PATH/empty

echo "Dotfiles Installed! Don't forget to setup environments and change the user's shell as needed!"
exec fish