#!/bin/sh
rel_dir="${PWD#$HOME/}"
echo "Configs relative to home in $rel_dir."

have() {
	which $1 >/dev/null 2>&1
}

link_file() {
	if [ ! -e "$HOME/$2" ]; then
		echo "Symlinking $HOME/$2 -> $3$rel_dir/$1…"
		ln -s "$3$rel_dir/$1" "$HOME/$2"
	else
		echo "$HOME/$2 already exists, skipping…"
	fi
}

export XDG_DATA_HOME="$HOME/.local/share"
export GNUPGHOME="$XDG_DATA_HOME/gnupg"

mkdir -p $HOME/.config
have cvs && link_file cvsrc .cvsrc
if have fossil; then
	echo "Setting global fossil settings…"

	fossil set --global autosync 0
	fossil set --global editor 'vim -c "se ft=gitcommit"'
	fossil set --global mv-rm-files 1

	if have gpg2; then
		gpg="gpg2"
	elif have gpg; then
		gpg="gpg"
	else
		gpg="false"
	fi

	gpg_key="7395312F"
	if $gpg --list-secret-keys $gpg_key >/dev/null 2>&1; then
		fossil set --global pgp-command \
			"$gpg -u $gpg_key --clearsign -o"
		fossil set --global clearsign 1
	else
		fossil unset --global pgp-command
		fossil unset --global clearsign
	fi
fi
have git && link_file git .config/git ../
if have gpg || have gpg2; then
	mkdir -p $HOME/.local/share/gnupg
	chmod 700 $HOME/.local/share/gnupg
	link_file gnupg/gpg.conf .local/share/gnupg/gpg.conf ../../../
	link_file gnupg/scdaemon.conf .local/share/gnupg/scdaemon.conf ../../../
	if have gpg2; then
		gpg="gpg2"
	else
		gpg="gpg"
	fi
	$gpg --import gnupg/keyring.asc
	$gpg --import-ownertrust gnupg/ownertrust
fi
have mpv && link_file mpv .config/mpv ../
have tmux && link_file tmux .config/tmux ../
have vim && link_file vim .config/vim ../
have yt-dlp && link_file yt-dlp .config/yt-dlp ../
have zsh && link_file zshrc .zshrc
if have ssh; then
	mkdir -p $HOME/.ssh
	link_file ssh/config .ssh/config ../
fi

if [ "$XDG_SESSION_DESKTOP" = "gnome" ]; then
	gsettings set org.gnome.desktop.interface color-scheme prefer-dark
	gsettings set org.gnome.desktop.interface cursor-blink false
	gsettings set org.gnome.desktop.interface monospace-font-name 'Cascadia Mono 10'
	gsettings set org.gnome.desktop.media-handling automount false
	gsettings set org.gnome.desktop.media-handling automount-open false
	gsettings set org.gnome.desktop.wm.preferences button-layout appmenu:minimize,close
	gsettings set org.gnome.mutter attach-modal-dialogs false

	dconf load /org/gnome/terminal/ <dconf/gnome-terminal
fi

if test x"$(uname -s)" = x"Darwin"; then
	for i in "Keyboard Layouts/"*; do
		dest="$HOME/Library/$i"
		# This does not like being symlinked…
		if [ ! -e "$dest" ]; then
			echo "Hardlinking $i -> $dest"
			ln "$i" "$dest"
		else
			echo "$dest already exists, skipping…"
		fi
	done
elif have startx; then
	link_file Xdefaults .Xdefaults
	link_file Xmodmap .Xmodmap
	link_file xinitrc .xinitrc
	link_file xscreensaver .xscreensaver
fi
