chiark / gitweb /
Directories: do not process dotfiles/dot itself (!)
[ian-dotfiles.git] / infra / makelinks
1 #!/bin/bash
2 #
3 # To start tracking a file,
4 #   cp ~/.screenrc dot/screenrc
5 #
6 # To sort out symlinks when things are clean
7 #   infra/makelinks install
8
9 set -e -o posix -o pipefail
10
11 badusage () {
12     echo >&2 "usage: $0 [-n|-v] list|setup|dirimport|dirmove|clean"
13     exit 18
14 }
15
16 real_act=''
17
18 while true; do
19     if [ $# = 0 ]; then break; fi
20     case "$1" in
21     -n) real_act=log_only ;;
22     -v) real_act=with_log ;;
23     -*) badusage ;;
24     *) break ;;
25     esac
26     shift
27 done
28
29 case "$#.$1" in
30 1.list|1.setup|1.import|1.dirimport|1.clean) ;;
31 *)  badusage ;;
32 esac
33
34 mode=$1; shift
35
36 dots=$( find dot -mindepth 1 -maxdepth 1 -name '[0-9a-zA-Z]*[0-9a-zA-Z]' )
37
38 basepath=$(pwd)
39 basepath=${basepath#$HOME/}
40
41 estatus=0
42
43 show () {
44     printf "%s\n" "$1"
45 }
46
47 good () {
48     if [ $mode = list ]; then
49         show "good: $dot: $1"
50     fi
51 }
52
53 bad () {
54     estatus=16
55     show "bad: $dot: $1" >&2
56 }
57
58 needs () {
59     if [ $mode = $1 ]; then
60         act=$real_act
61     else
62         show "needs $1: $prhome: $2"
63         act=:
64     fi
65 }
66
67 log_only () {
68     echo "x $*"
69 }
70
71 with_log () {
72     log_only "$@"
73     "$@"
74 }
75
76 for dot in $dots; do
77     underhome=".${dot#dot/}"
78     inhome="$HOME/$underhome"
79     prhome="~/$underhome"
80     if [ "$inhome" -ef "$dot" ]; then
81         good "already symlinked here"
82     elif [ -h "$inhome" ]; then
83         bad "wrong symlink target"
84     elif ! [ -e "$inhome" ]; then
85         needs setup "absent here"
86         $act ln -s "$basepath/$dot" "$inhome"
87     elif [ -f "$inhome" ] && [ -f "$dot" ]; then
88         if cmp -s "$dot" "$inhome"; then
89             needs setup "identical here but not yet symlinked"
90             $act rm -f "$inhome"~
91             $act ln -s "$basepath/$dot" "$inhome"~
92             $act mv -f "$inhome"~ "$inhome"
93         else
94             needs import "modified here"
95             $act rm -f "$dot"~
96             $act cp "$inhome" "$dot"~
97             $act mv -f "$dot"~ "$dot"
98         fi
99     elif [ -d "$inhome" ] && [ -d "$dot" ]; then
100         needs dirimport "directory here not yet symlinked"
101         $act mv "$dot" "$dot~"
102         $act ln -s "$basepath/$dot" "$inhome"~
103         $act mv "$inhome" "$dot"
104         $act mv "$inhome~" "$inhome"
105         $act rm -rf "$dot~"
106     else
107         bad "mismatched file types"
108     fi
109 done
110
111 brokens=$(
112     cd $HOME
113     find -L .[0-9a-zA-Z]* -maxdepth 0 -xdev -type l -lname "$basepath/dot/*"
114 )
115 for underhome in $brokens; do
116     inhome="$HOME/$underhome"
117     prhome="~/$underhome"
118     needs clean "symlink to removed file in dot/"
119     $act rm -f "$inhome"
120 done