aboutsummaryrefslogtreecommitdiff
path: root/updatedots
blob: dd9d834246b7a3d734aa794b043b25315d630a74 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/bin/bash
# Simple dotfile linking script.
# Partly inspired by dotsync (https://github.com/dotphiles/dotsync).
#
# This script takes files in a version-controllable "dotdir" directory
# and creates corresponding symlinks in the user's home directory.
# Any existing files in the home directory are backed up before being
# replaced with a symlink.

set -o nounset

# Root directory of dotfiles project (directory containing this script)
basedir="$(dirname "$(readlink -f "$0")")"

# Directory containing all dotfiles that will be linked to $homedir
dotdir="$basedir/home"

# Directory into which files will be linked
homedir="$HOME"

# Directory into which any pre-existing dotfiles will be copied
backupdir="$homedir/.updatedots-backup"

# Dotfiles relative to $dotdir
mapfile -t rdotfiles < <(find "$dotdir" -mindepth 1 -type f,l -printf '%P\n')

# Link dotfiles to home directory, backing up any collisions
create_links() {
    [[ -e $backupdir ]] || mkdir "$backupdir"
    if [[ -n $(ls --almost-all "$backupdir") ]]; then
	echo "Backup directory $backupdir is not empty. Aborting." >&2
	exit 1
    fi

    local moved=0

    for relative in "${rdotfiles[@]}"; do
	local src="$dotdir/$relative"
	local dest="$homedir/$relative"

	mkdir -p "$(dirname "$dest")"

	if [[ ! -L "$dest" ]] || [[ $(readlink -f "$dest") != $(readlink -f "$src") ]]; then
	    if [[ -e "$dest" ]]; then
		local bdest="$backupdir/$relative"
		mkdir -p "$(dirname "$bdest")"
		mv "$dest" "$bdest"
		moved=$((moved+1))
		echo "$relative: backed up original $dest to $bdest"
	    fi
	    ln --symbolic --relative "$src" "$dest"
	    echo "$relative: linked to $dest"
	fi
    done

    if [ "$moved" -gt 0 ]; then
	echo "NOTE: $moved files were moved to $backupdir" >&2
    fi
}

create_links