-
Notifications
You must be signed in to change notification settings - Fork 1
/
setuplib
446 lines (389 loc) · 12.1 KB
/
setuplib
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# Constants and support functions to be sourced by setup scripts
#
# Copyright (C) 2015 Rodrigo Silva (MestreLion) <[email protected]>
# License: GPLv3 or later. See <http://www.gnu.org/licenses/gpl.html>
#
# Use setup.d/template to create new setup scripts
#------------------------------------------------------------------------------
set -Eeuo pipefail # exit on any error
trap '>&2 echo "error: line $LINENO, status $?: $BASH_COMMAND"' ERR
#------------------------------------------------------------------------------
usage() {
# Calling scripts are expected to set DESCRIPTION and ARGS
local error=${1:-0}
# shellcheck disable=SC2153
local usage="Usage: ${0##*/}${ARGS:+" ${ARGS}"}"
if ((error)); then
echo "$usage" >&2
exit "$error"
else
echo -e "${DESCRIPTION:+"${DESCRIPTION}\\n"}${usage}"
exit
fi
}
# Pre-parse for -h|--help, ignoring if after '--'
for arg in "$@"; do
if [[ "$arg" == '--' ]]; then break; fi
if [[ "$arg" == "-h" || "$arg" == "--help" ]]; then usage; fi
done
unset arg
# Handy XDG vars with their defaults
CONFIG_HOME=${XDG_CONFIG_HOME:-"$HOME/.config"}
# shellcheck disable=SC2034
DATA_HOME=${XDG_DATA_HOME:-"$HOME/.local/share"}
# shellcheck disable=SC2034
BIN_HOME=${XDG_BIN_HOME:-"$HOME/.local/bin"} # Not official, but widely used
# shellcheck disable=SC2034
STATE_HOME=${XDG_STATE_HOME:-"$HOME/.local/state"}
# Set and source the config file, silently ignoring if it does not exist
# Factory default is intentionally not affected by SETUP_SLUG
# Keep it in sync with bootstrap.sh!
SETEN_CONFIG=${SETEN_CONFIG:-"${CONFIG_HOME}/seten/seten.conf"}
include-config() {
local config
for config in "$@"; do
if [[ -d "$config" ]]; then
include-config "$config"/*{.conf,/}
fi
if ! [[ -f "$config" && -r "$config" ]]; then
continue
fi
pushd "$(dirname "$config")" >/dev/null
# shellcheck source=seten.template.conf
source "$(basename "$config")"
popd >/dev/null
done
}
include-config "$SETEN_CONFIG"
#------------------------------------------------------------------------------
# Setup engine
# shellcheck disable=SC2120
username() { getent passwd "${1:-$USER}" | cut -d: -f5 | cut -d, -f1; }
absdir() { dirname "$(readlink -f "${1:-$0}")"; }
# See README's FAQ on why the vars are named SETUP_* instead of SETEN_*
# Keep in sync with seten.template.conf and bootstrap.sh!
slug=${SETUP_SLUG:-}; slug=${slug##*/}; slug=${slug## /_}
SETUP_SLUG=${slug:-'seten'}; unset slug
SETUP_NAME=${SETUP_NAME:-'Seten'}
SETUP_VERBOSE=${SETUP_VERBOSE:-1}
SETUP_DEBUG=${SETUP_DEBUG:-0}
SETUP_INTERACTIVE=${SETUP_INTERACTIVE:-1}
SETUP_DRYRUN=${SETUP_DRYRUN:-0}
SETUP_USER=${SETUP_USER:-${USER,,}}
SETUP_USERNAME=${SETUP_USERNAME:-$(username)}
SETUP_LIBS_DIR=${SETUP_LIBS_DIR:-"$(absdir "${BASH_SOURCE[0]}")/lib"}
# Intentionally not configurable
# shellcheck disable=SC2034
SETUP_WEBSITE='https://github.com/MestreLion/seten'
# shellcheck disable=SC2034
SETUP_SCRIPT=${0##*/}
#------------------------------------------------------------------------------
# Platform info
# Distro name, lowercase: ubuntu
if [[ -z "${SETUP_DISTRO:-}" ]]; then
SETUP_DISTRO=$(lsb_release -si)
SETUP_DISTRO=${SETUP_DISTRO,,}
fi
# Distro numeric release version: 18.04
# Use version_{lesser,greater}() to compare!
if [[ -z "${SETUP_RELEASE:-}" ]]; then
SETUP_RELEASE=$(lsb_release -sr)
fi
if [[ -z "${SETUP_CODENAME:-}" ]]; then
SETUP_CODENAME=$(lsb_release -sc)
SETUP_CODENAME=${SETUP_CODENAME//\./}
fi
if [[ -z "${SETUP_BITS:-}" ]]; then
if [[ "$(arch)" == 'x86_64' ]]; then
SETUP_BITS=64
else
SETUP_BITS=32
fi
fi
if [[ -z "${SETUP_ARCH:-}" ]]; then
SETUP_ARCH=$(arch)
fi
if [[ -z "${SETUP_APT_ARCH:-}" ]]; then
# See dpkg-architecture
SETUP_APT_ARCH=$(
awk -v arch="$SETUP_ARCH" '/^#/{next} $2 == arch{print $1}' \
/usr/share/dpkg/cputable 2>/dev/null || true
)
fi
# Desktop environment
SETUP_DESKTOP=${SETUP_DESKTOP:-${XDG_SESSION_DESKTOP:-${XDG_CURRENT_DESKTOP:-}}}
# Encapsulates the mess that DE detection was, is, or will ever be...
# Without arguments, check if in a Desktop Environment at all
# Subshell is intentional so we don't have to save/restore IFS
# Case-insensitive comparison
# https://unix.stackexchange.com/a/645761/4919
is_desktop_environment() (
local de=${1:-}
local DEs=${XDG_CURRENT_DESKTOP:-}
# Shortcut: If "$de" is empty, check if empty DEs
if [[ -z "$de" ]]; then if [[ "$DEs" ]]; then return; else return 1; fi; fi
# Lowercase both
de=${de,,}
DEs=${DEs,,}
# Check de against each DEs component
IFS=:; for DE in $DEs; do if [[ "$de" == "$DE" ]]; then return; fi; done
# Not found
return 1
)
#------------------------------------------------------------------------------
# Source libraries in SETUP_LIBS_DIR
# Usage: include LIB...
include() {
local lib
for lib in "$@"; do
lib=${SETUP_LIBS_DIR}/${lib}
if ! [[ -f "$lib" && -r "$lib" ]]; then
fatal "Library not accessible: ${lib}"
fi
# shellcheck source=lib/dbus # any lib will do
source "$lib"
done
}
setup_run() {
if ((SETUP_DRYRUN)); then
echo "$@" >&2
else
"$@"
fi
}
#------------------------------------------------------------------------------
exists() { type "$@" &>/dev/null; }
escape() { printf '%q' "$@"; }
relpath() { python3 -c 'import sys,os;print(os.path.relpath(*sys.argv[1:3]))' "$@"; }
try() { "$@" 2>/dev/null || :; }
bold() { try tput bold; printf '%s' "$@"; try tput sgr0; echo; }
color() { if (($# > 1)); then try tput setaf "$1"; shift; bold "$@"; fi; }
red() { color 1 "$@"; }
green() { color 2 "$@"; }
yellow() { color 3 "$@"; }
blue() { color 4 "$@"; }
white() { color 7 "$@"; }
fatal() { red "${0##*/}: fatal${1:+: $@}" >&2; exit 1; }
error() { red "error${1:+: $@}" >&2; }
warning() { yellow "warning${1:+: $@}" >&2; }
message() { if ((SETUP_VERBOSE)); then green "* $*"; fi; }
debugmsg(){ if ((SETUP_DEBUG)); then echo "$@" >&2; fi; }
debugvar(){ if ((SETUP_DEBUG)); then declare -p "$@" >&2; fi; }
is_root() { (( EUID == 0 )); } # EUID set by bash. POSIX: [ "$(id -u)" -eq 0 ]
user_exists() { id -- "${1:-}" &>/dev/null; } # getent passwd -- "${1:-}" >/dev/null
if exists getent; then
# Alternative for user_home(): sh -c "echo ~${1:-${USER:-$(id -un)}}"
user_home() { getent passwd -- "${1:-$(id -un)}" | cut -d: -f6; }
group_exists(){ getent group -- "${1:-}" >/dev/null; }
else
user_home() { awk -F: -v uid=$EUID '$3 == uid {print $6}' /etc/passwd; }
group_exists(){ grep -q -- "^${1:-}:" /etc/group; }
fi
create_system_user() {
local user=$1
local name=${2:-}
message "Create system user '$user'"
# if user_exists "$user"; then return; fi
useropts=(
--system # implies --shell /usr/sbin/nologin
--group # create its group, otherwise system users are put in nogroup
--quiet # no error if system user already exists
--home "/var/lib/${user}" # default /home/<USER> even for system
)
if [[ "$name" ]]; then
useropts+=( --gecos "$name" )
fi
setup_run sudo adduser "${useropts[@]}" -- "$user"
}
now() { date +%Y%m%d%H%M%S; }
bakfile() { echo "${1:-}.${SETUP_SLUG}.$(now).bak"; }
backup_file() {
local source=$1
local target=${2:-}
if ! [[ -f "$source" ]]; then
return
fi
if [[ -z "$target" ]]; then
# Do not create another backup if one already exists
local previous=("${source}.${SETUP_SLUG}".*.bak)
if [[ -e "${previous[0]}" ]]; then
return
fi
target=$(bakfile "$source")
fi
setup_run sudo_for "$target" cp -p --no-clobber -- "$source" "$target"
}
create_temp_dir() {
# Usage: create_temp_dir; ... "$TEMP_DIR" ...
# Last created dir is assigned to TEMP_DIR
# Do NOT use in a subshell!
TEMP_DIR=$(mktemp --directory) || fatal "could not create temp dir"
declare -ga _TEMP_DIRS; _TEMP_DIRS+=( "$TEMP_DIR" )
trap 'rm -rvf -- "${_TEMP_DIRS[@]}"' EXIT
}
# shellcheck disable=SC2120
signature() {
local action=${1:-created}
local comment=${2:-#}
echo "${comment} ${action^} by ${SETUP_NAME} ${SETUP_SCRIPT}"
echo "${comment} ${SETUP_WEBSITE}"
}
sudo_for() {
local path=$1; shift
if ! [[ -e "$path" ]]; then
path=$(dirname -- "$(realpath "$path")")
fi
if [[ -w "$path" ]]; then
"$@"
return
fi
sudo "$@"
}
argument() {
if ! [[ "${1:-}" ]]; then
echo "Missing required argument${2:+" ${2}"}" >&2
usage 1
fi
}
integer() {
if ! [[ "$1" != *[!0-9]* ]]; then
echo "${2:+"${2} is "}not an integer: $1" >&2
usage 1
fi
}
# Usage: declare -[g]A mymap=$(copy_map 'MYMAP')
# Requires Bash 4.4
copy_map() {
local map
map=$(declare -p "$1" 2>/dev/null || echo '()')
echo "${map#*=}"
}
confirm() {
# Non-empty garbage will always evaluate to and behave as NO
local message=${1:-"Confirm?"}
local default=NO
if ((SETUP_INTERACTIVE)); then
read -rp "$message (y/n, default $default): " resp
case "${resp:-$default}" in [Yy]*);; *) return 1;; esac
fi
}
download() {
local url=$1
local outdir=$2
local user=${3:-}
local uarg=(); if [[ "$user" ]]; then uarg=(-u "$user"); fi
wgetcmd=(
setup_run sudo_for "$outdir" "${uarg[@]}"
wget -NP "$outdir" --content-disposition --trust-server-names -- "$url"
)
# run once to download, again to print name.
# It won't actually re-download thanks to -N
"${wgetcmd[@]}"
"${wgetcmd[@]}" 2>&1 | awk -F"[‘’]" '$2 {print $2}'
}
# NOTE: Given install_package() and exists(),
# required() and required_install() are DEPRECATED!
required() {
local cmd=$1
local msg=${2:-Missing required command: $cmd}
if ! exists "$cmd"; then
fatal "$msg"
fi
}
required_install() {
# Install a package if a command is missing
# Usage: required_install <PACKAGE> [COMMAND]
# By default COMMAND == PACKAGE
# For simply installing missing packages, use package_install()
local pkg=$1
local cmd=${2:-$pkg}
if ! exists "$cmd"; then
$SETUP_RUN sudo apt install -y -- "$pkg"
fi
}
version_sort() {
# print one argument per line sorted on version ordering
printf "%s\n" "$@" | LC_ALL=C sort --version-sort
}
version_compare() {
# Usage: version_compare <greater|lesser> version [versions...]
# Return 0 if version is the greatest (or the least) of all versions,
# non-zero otherwise
if [[ "$1" == "greater" ]]; then
local cmd=(tail -n1)
else
local cmd=(head -n1)
fi
shift
if ! [[ "$(version_sort "$@" | "${cmd[@]}")" == "$1" ]]; then
return 1
fi
}
version_greater() {
# Usage: version_greater <version> <reference>
# Return 0 if version is greater or equal than reference,
# non-zero otherwise
if ! version_compare "greater" "$1" "$2"; then return 1; fi
}
version_lesser() {
# Usage: version_lesser <version> <reference>
# Return 0 if version is lesser or equal than reference,
# non-zero otherwise
if ! version_compare "lesser" "$1" "$2"; then return 1; fi
}
package_version() {
dpkg-query --showformat='${Version}' --show "$1" 2>/dev/null
}
package_installed() {
local ok
ok=$(package_version "$1") && [[ "$ok" ]]
}
install_package() {
# Install all non-existing packages in a single command
# Usage: package_install [PACKAGE...]
local pkg=
local pkgs=()
for pkg in "$@"; do
if ! package_installed "$pkg"; then pkgs+=("$pkg"); fi
done
if (("${#pkgs[@]}")); then
setup_run sudo apt install -y "${pkgs[@]}"
fi
}
package_install() {
echo >&2 "package_install() is deprecated, use install_package() instead"
}
add_ppa() {
# WIP!
# See nginx, https://blog.zackad.dev/en/2017/08/17/add-ppa-simple-way.html
# move to lib/ppa.py
local ppa=${1#ppa:} # user/slug, or ppa:user/slug
local user=
local key_url=$2 # gotta parse launchpad!
local key=/etc/apt/keyrings/${ppa//\//-}.gpg
local repo=https://ppa.launchpadcontent.net/${ppa}/ubuntu
local line; line="[arch=${SETUP_APT_ARCH} signed-by=$(escape "$key")] ${repo} ${SETUP_CODENAME} main"
message "Add PPA $ppa"
setup_run sudo tee /etc/apt/sources.list.d/nginx-mainline.list <<-EOF
$(signature)
deb ${line}
deb-src ${line}
EOF
message "Add PPA signing key"
curl -Ss "$key_url" | gpg --dearmor | setup_run sudo tee -- "$key" >/dev/null
}
package_remove() {
# Remove all existing packages in a single command
# Usage: package_remove [PACKAGE...]
local pkg=
local pkgs=()
for pkg in "$@"; do
if package_installed "$pkg"; then pkgs+=("$pkg"); fi
done
if (("${#pkgs[@]}")); then
setup_run sudo apt remove -y "${pkgs[@]}"
fi
}
is_online() {
ping -c 1 www.google.com >/dev/null 2>&1
}