-
Notifications
You must be signed in to change notification settings - Fork 0
/
base.sh
executable file
·147 lines (123 loc) · 2.99 KB
/
base.sh
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#!/usr/bin/env bash
init() {
DEFAULT_CONFIG=${XDG_CONFIG_HOME:-$HOME/.config}
while getopts ':c:d:s:' opt; do
case $opt in
c)
cmd=$OPTARG
;;
d)
dst_conf=$OPTARG
;;
s)
src_conf=$OPTARG
;;
\?)
fail "Invalid option -$OPTARG." >&2
;;
esac
done
src_conf=${src_conf:-$(cd -P "$(dirname "$0")" && pwd -P)}
dst_conf=${dst_conf:-$DEFAULT_CONFIG/${src_conf##*/}}
cmd=${cmd:-${src_conf##*/}}
}
user() {
printf '[ \033[0;35m??\033[0m ] %b\n' "$1"
}
warn() {
printf '[ \033[0;33m!!\033[0m ] %b\n' "$1"
}
info() {
printf '[ \033[0;34m**\033[0m ] %b\n' "$1"
}
success() {
printf '[ \033[0;32mOK\033[0m ] %b\n' "$1"
}
fail() {
printf '[ \033[0;31mXX\033[0m ] %b\n' "$1"
}
link_file() {
local src=$1 dst=$2
local overwrite=false backup=false skip=false
local action=
local current_src
local seconds=$(date +%s)
if [[ -f $dst || -d $dst || -L $dst ]]; then
current_src=$(readlink "$dst")
if [[ $current_src == "$src" ]]; then
skip=true
else
user "File already exists: $dst (src=$(basename "$src")), what do you want to do?\n\
[s]kip, [o]verwrite, [b]ackup?"
read -r -n 1 action
case $action in
o)
overwrite=true
;;
b)
backup=true
;;
s)
skip=true
;;
*) ;;
esac
fi
if [[ $overwrite == true ]]; then
\rm -rf "$dst"
success "Removed $dst"
fi
if [[ $backup == true ]]; then
mv "$dst" "${dst}.backup.$seconds"
success "Moved $dst to ${dst}.backup.$seconds"
fi
if [[ $skip == true ]]; then
info "Skipped to link $src to $dst"
return 0
fi
fi
if [[ $skip != true ]]; then # "false" or empty
if ln -s "$src" "$dst"; then
success "Linked $src to $dst"
return 0
else
fail "Fail to link $src to $dst"
return 1
fi
fi
}
check() {
if [[ -z $(command -v $cmd) ]]; then
warn "command not found: $cmd."
return 1
fi
}
do_install() {
mkdir -p "$dst_conf" 2>/dev/null
for file in $(ls $src_conf -I install.sh); do
link_file "$src_conf/$file" "$dst_conf/$file"
done
}
install() {
init "$@"
if [[ -z $src_conf ]]; then
fail 'Without initialization, fail to install.'
return 1
fi
if ! check; then
return 0
fi
success "Installing $cmd config."
do_install
if [ "$?" = "0" ]; then
success "Installed $cmd config successfully."
return 0
else
fail "Failed to install $cmd config!"
return 1
fi
}
if [[ $(basename "$0") == base.sh ]]; then
fail 'Can not run a base shell.'
exit 1
fi