dotfiles/setup
2025-06-25 00:26:07 +02:00

141 lines
3.8 KiB
Bash
Executable file
Vendored

#!/usr/bin/env bash
args() {
while [ -n "$1" ]; do
case "$1" in
"-h" | "--help")
echo "$0 [OPTIONS] -- Dotfile management script"
echo ""
echo "options:"
echo " -h/--help Show this dialog"
echo " -p/--pretend Preview changes without application"
echo " -u/--uninstall Uninstall symlinks and restore backups"
echo " -n/--no-backup Do not back up existing directories"
echo ""
echo "origin: https://git.caem.dev/caem/dotfiles"
exit 0
;;
"-p" | "--pretend")
PRETEND_MODE=1
;;
"-u" | "--uninstall")
UNINSTALL_MODE=1
;;
"-n" | "--no-backup")
NO_BACKUP=1
;;
*)
>&2 echo "Unknown option '$1'. Run with --help for a list of valid options."
exit 1
;;
esac
shift
done
}
install_map=(
".emacs.d" "$HOME/.emacs.d"
".config/emacs" "$HOME/.config/emacs"
".config/fastfetch" "$HOME/.config/fastfetch"
".config/ghostty" "$HOME/.config/ghostty"
".zshrc" "$HOME/.zshrc"
".guile" "$HOME/.guile"
".profile" "$HOME/.profile"
)
install() {
for ((i = 0 ; i < "${#install_map[@]}" ; i += 2)); do
local src
src="$(realpath "${install_map[$i]}")"
local dst="${install_map[$((i + 1))]}"
if [ "$(readlink "$dst")" = "$(realpath "$src")" ]; then
echo "Skipping $src as it already is symlinked"
continue
fi
if [ -e "$dst" ]; then
if [ -n "$NO_BACKUP" ]; then
>&2 echo "Cannot continue as $dst already exists"
else
local backup
backup="$(basename "$dst")"
if [[ $backup != "."* ]]; then
backup=".${backup}"
fi
backup="$(dirname "$dst")/${backup}.backup"
if [ -e "$backup" ]; then
>&2 echo "Cannot continue as backup already exists at $backup"
exit 1
fi
if [ -z "$PRETEND_MODE" ]; then
cp -r "$dst" "$backup"
fi
echo "backup $dst -> $backup"
fi
fi
if [ -z "$PRETEND_MODE" ]; then
rm -rf "$dst"
ln -s "$(realpath "$src")" "$dst"
fi
echo "symlink $dst -> $src"
done
}
uninstall() {
for ((i = 0 ; i < "${#install_map[@]}" ; i += 2)); do
local src
src="$(realpath "${install_map[$i]}")"
local dst="${install_map[$((i + 1))]}"
if [ ! -h "$dst" ]; then
echo "Skipping $dst as it is not a symlink"
continue
fi
if [ "$(readlink -f "$dst")" = "$(realpath "$src")" ]; then
if [ -z "$PRETEND_MODE" ]; then
unlink "$dst"
fi
echo "remove link $dst"
local backup
backup="$(basename "$dst")"
if [[ $backup != "."* ]]; then
backup=".${backup}"
fi
backup="$(dirname "$dst")/${backup}.backup"
if [ -e "$backup" ]; then
if [ -z "$PRETEND_MODE" ]; then
mv "$backup" "$dst"
fi
echo "restore $backup -> $dst"
fi
else
echo "Skipping $dst as it is not symlinked"
continue
fi
done
}
main() {
args "$@"
if [ -n "$PRETEND_MODE" ]; then
echo "(pretend)"
fi
if [ -z "$UNINSTALL_MODE" ]; then
install
else
uninstall
fi
}
set -e
main "$@"