-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbl-includes
549 lines (494 loc) · 17.3 KB
/
bl-includes
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# bl-includes - Variables and functions commonly used in custom scripts
# for Bunsen Labs Linux.
# Copyright (C) 2012 Philip Newborough <[email protected]>
# Copyright (C) 2013 Aleks-Daniel Jakimenko
# Copyright (C) 2016 xaos52 <[email protected]>
# Copyright (C) 2015-2023 John Crawley <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# These functions can be used in user scripts too, by first sourcing this file, eg:
# BL_COMMON_LIBDIR='/usr/lib/bunsen/common'
# if ! . "$BL_COMMON_LIBDIR/bl-includes" 2> /dev/null; then
# echo $"Error: Failed to locate bl-includes in $BL_COMMON_LIBDIR" >&2
# exit 1
# fi
# NOTE: Do not source this file in non-Bash shell scripts,
# it uses some "bashisms".
# shellcheck shell=bash
######## jgmenu versions of OB menu creation functions #################
# Associative array menu_content is generated.
# Submenu content is stored under index of its tag,
# 'root' indexes the root menu.
# The content of menu_content is printed out with jgmenuEnd()
# Put an item in the root menu or any submenu.
# Usage: jgmenuItem tag label command
# Tag 'root' indicates root menu item.
jgmenuItem() {
_jgmenuSetHeader "$1"
menu_content[$1]+="\"\"\"$(pangoEscape "${2}")\"\"\",\"\"\"${3}\"\"\""$'\n'
}
# Add a separator.
# Usage: jgmenuSeparator tag [label]
jgmenuSeparator() {
_jgmenuSetHeader "$1"
menu_content[$1]+="^sep($(pangoEscape "${2-}"))"$'\n'
}
# Put a checkout() for a submenu in the root menu or any submenu.
# Usage jgmenuSubmenu tag(parentmenu) tag(submenu) label
jgmenuSubmenu() {
_jgmenuSetHeader "$1"
menu_content[$1]+="\"\"\"$(pangoEscape "${3}")\"\"\",^checkout($2)"$'\n'
}
# Print root menu, then submenus.
jgmenuEnd() {
printf '%s\n' "${menu_content[root]}"
unset 'menu_content[root]'
for i in "${!menu_content[@]}"
do
printf '%s\n' "${menu_content[$i]}"
done
unset 'menu_content'
}
# Initiates array and sets header for submenu when first content is added.
# Do not call this function directly.
# Usage: _jgmenuSetHeader tag
_jgmenuSetHeader(){
declare -Ag menu_content
[[ $1 != root && -z ${menu_content[$1]} ]] && {
menu_content[$1]="^tag($1)"$'\nBack,^back()\n'
}
}
pangoEscape() {
local string="${1//&/\&}"
string="${string//</\<}"
string="${string//>/\>}"
printf '%s' "$string"
}
########## end jgmenu functions ################
####### Functions to generate Openbox menus. ###########################
menuStart() {
echo ' <openbox_pipe_menu>'
}
# Usage: menuItem label command
menuItem() {
echo " <item label=\"$(OBlabelEscape "$1")\">
<action name=\"Execute\">
<command>
$(XMLescape "$2")
</command>
</action>
</item>"
}
# Usage: menuSeparator [label]
menuSeparator() {
if [[ ${1-} ]]; then
echo " <separator label=\"$(OBlabelEscape "$1")\"/>"
else
echo ' <separator/>'
fi
}
# Usage menuSubmenu id label # http://openbox.org/wiki/Help:Menus
menuSubmenu() {
echo " <menu id=\"$(XMLescape "$1")\" label=\"$(OBlabelEscape "$2")\">"
}
menuSubmenuEnd() {
echo ' </menu>'
}
menuEnd() {
echo ' </openbox_pipe_menu>'
}
# escape special characters
XMLescape() {
local string="${1//&/\&}"
string="${string//</\<}"
string="${string//>/\>}"
string="${string//\"/\"}"
string="${string//\'/\'}"
printf '%s' "$string"
}
OBlabelEscape() {
local string="$(XMLescape "$1")"
printf '%s' "${string//_/__}"
}
########################################################################
# rerun the calling script in terminal if necessary
# Usage: terminalCheck [ -T title ] [arguments...]
# If the calling script takes arguments, pass them to this function:
# terminalCheck "$@"
terminalCheck() {
if ! [[ -t 0 && -t 1 && -t 2 ]]; then # not attached to terminal
if [[ -n $DISPLAY ]]; then # running X
local -a termcmd
local termname
if [[ ${1-} = '-T' ]];then
local title=${2-}
shift 2
fi
termname=$( readlink -f "$( which x-terminal-emulator )" )
termname=${termname##*/}
badterm_msg="$0: $termname is not supported.
Please choose a different x-terminal-emulator."
case $termname # cope with terminal inconsistencies
in
lxterminal)
termcmd=(lxterminal --no-remote) # otherwise lxterminal does not start a new process
[[ -n $title ]] && termcmd+=(-T "$title")
termcmd+=(-e)
;;
mate-terminal.wrapper)
termcmd=(mate-terminal --disable-factory) # mate-terminal.wrapper does not support --disable-factory
[[ -n $title ]] && termcmd+=(-t "$title") # but mate-terminal needs -t for -T option
termcmd+=(-x)
;;
# gnome terminal now waits if invoked as x-terminal-emulator
# gnome-terminal.wrapper)
# termcmd=(gnome-terminal --wait) # gnome-terminal.wrapper does not support --wait
# [[ -n $title ]] && termcmd+=(-t "$title") # but gnome-terminal needs -t for -T option
# termcmd+=(--) # -x is deprecated
# ;;
tilix.wrapper)
termcmd=(tilix --new-process) # tilix.wrapper does not support --new-process
[[ -n $title ]] && termcmd+=(-t "$title") # but tilix needs -t for -T option
termcmd+=(-e)
;;
qterminal|terminology)
echo "$badterm_msg" >&2
exit 1
;;
*)
termcmd=(x-terminal-emulator) # the normal case
[[ -n $title ]] && termcmd+=(-T "$title")
termcmd+=(-e)
;;
esac
exec "${termcmd[@]}" "$0" "$@"
else
echo "$0: no terminal" >&2
exit 1
fi
fi
}
# Usage: createFlag filename
createFlag() {
mkdir -p "$HOME/.config/bunsen"
touch "$HOME/.config/bunsen/$1"
}
# Check the connection by downloading a file from ftp.debian.org. No disk space used.
# Usage: connectiontest [attempts]
# If attempt count is not specified or 0, then it will loop forever and exit(!) your main program with 1 exit status.
connectiontest() {
local TEXT_CHECKING='Checking internet connection...'
local TEXT_FAILED='Internet connection test failed!'
local TEXT_ASK_RETRY=$'\n\nThis script requires a working internet connection. Please configure your internet connection, then hit "Enter" to continue, else hit "q" to quit.'
local TEXT_ABORT='Script aborted.'
local TEXT_OK='Internet connection test passed!'
local -i i attempts=${1-0}
for (( i=0; i < attempts || attempts == 0; i++ )); do
say "$TEXT_CHECKING"
if wget -O - 'http://ftp.debian.org/debian/README' &> /dev/null; then
say "$TEXT_OK" 1
return 0
fi
say "$TEXT_FAILED"
if (( i == attempts - 1 )); then # if last attempt
return 1
elif prompt "$TEXT_ASK_RETRY" Q; then # if user wants to quit
say "$TEXT_ABORT" 2
(( attempts == 0 )) && exit 1 || return 1
fi
tput clear
done
}
# Check for availability of commands used in script.
# Usage: declareDependencies command [command...]
declareDependencies(){
local missing_commands=() i=
for i in "$@"
do
hash "$i" 2>/dev/null || missing_commands+=(" $i")
done
[[ ${missing_commands[0]} ]] && errorExit "This script requires the following commands: ${missing_commands[*]}
Please install the packages containing the missing commands
and rerun the script."
}
########################################################################
# User interface functions.
# Usage: say text [delayAfterText|pause]
say() {
local width=$(tput cols 2>/dev/tty)
fold -s -w $((width - 3)) <<< "${1-}" | sed 's/^/ /' # wraps text nicely and adds two leading spaces
if [[ ${2-} = 'pause' ]]
then
echo $'\nPress any key to continue.'
read -srn1
else
sleep "${2:-0}"
fi
}
# Usage errorExit message [details]
errorExit() {
say $'\n'"$1"$'\n' '1' >&2
[[ $(type -t log) = 'function' ]] && {
log "######## ERROR ########
$1"
}
[[ ${2-} ]] && {
while true
do
local REPLY
read -rn1 -p ' Press "d" for details (q to quit) '
[[ ${REPLY^} = Q ]] && exit 1
[[ ${REPLY^} = D ]] && {
echo $'\n\n'
#tput setaf 1
echo "ERROR MESSAGE:
$2
------------------------------------" >&2
#tput sgr0
say "
Would you like to quit now, or continue anyway?
(Be careful!)
Enter \"q\" to quit, \"c\" to continue:
"
read -r
[[ ${REPLY^} = Q ]] && exit 1
[[ ${REPLY^} = C ]] && return 0
}
done
}
say 'Press any key to exit.'
read -srn1
exit 1
}
# Usage: prompt text [ Y | N | Q | <string> ]
prompt() {
local answer prompt default test
if [[ ${2-} && ${2^} = Q ]]; then
while true; do
read -srn1 -p "$1" answer
echo
[[ ${answer^} = Q ]] && return 0
[[ ! $answer ]] && return 1
done
fi
if [[ ! ${2-} || ${2^} = Y ]]; then
prompt='Y/n'
default='Y'
elif [[ ${2^} = N ]]; then
prompt='y/N'
default='N'
else
prompt=
default=
fi
while true; do
read -r -p "$1 ${prompt:+[$prompt] }" answer
if [[ ! $prompt && ! $default ]]; then
test=${2-}
# allow for quotes round string (may be unbalanced)
# case-insensitive comparison
if [[ ${answer^^} =~ [\'\"]?${test^^}[\'\"]? ]]; then
echo
return 0
elif [[ ${answer^} = Q ]]; then
echo
return 1
else
continue
fi
fi
[[ ! $answer ]] &&
answer=$default
if [[ ${answer^} = Y || ${answer^^} = YES ]]; then
echo
return 0
elif [[ ${answer^} = N || ${answer^^} = NO ]]; then
echo
return 1
fi
done
}
# Usage: promptInstall name description [--apt-get-option] package [package...]
# To have some defined function - functionname - run first, use:
# promptInstall --setup functionname name desc...
promptInstall() {
local setupFunction=
if [[ $1 = '--setup' ]]; then
if [[ -n ${2-} && $(type -t "$2") = 'function' ]]; then
setupFunction="$2"
shift 2
else
say "Error: ${2-} is not a function."
return 1
fi
fi
tput clear
local title="INSTALL ${1^^}"
say "
$title
${title//?/-}
$2
"
prompt ' Run the installer now?' || return 1
tput clear
connectiontest || return 1
if [[ -n $setupFunction ]]; then
"$setupFunction" || return 1 # run setup function if it exists
fi
tput clear
say 'Updating sources...' 1
safeUpdate || say 'Continuing in spite of update problems...' 3
tput clear
say 'Installing package...' 1
safeInstall "${@:3}" || return 1
tput clear
say "
$1 has been installed successfully.
Hit any key to exit..."
read -srn1
return 0
}
########################################################################
# Package handling functions.
# outputs pin value and origin repo url if package is installed.
# returns 1 if package is not installed
# Usage: checkOrigin package
checkOrigin() {
apt-cache policy "$1" | sed -nr '/\*\*\*/ {n;s/^[ \t]*([0-9]+[ \t]+[^ \t]+).*$/\1/p;q0};${q1}'
}
# outputs version of installed package
# returns 1 if package is not installed
# Usage: checkVersion package
checkVersion() {
#apt-cache policy $1 | sed -nr '/\*\*\*/ {s/^[ \t]*\*\*\*[ \t]+([0-9a-z:.+~-]+)[ \t]+.*$/\1/p;q0};${q1}'
dpkg-query --show --showformat='${Version}' "$1" 2>/dev/null
}
# returns success if all packages are already installed
# Usage: allInstalled package [package...]
allInstalled() {
local pkg=
for pkg in "$@"
do
[[ $(dpkg-query --show --showformat='${db:Status-Abbrev}' "$pkg" 2>/dev/null) =~ ^(i|h)i' '$ ]] || return 1
# NB dpkg will change soon, possibly making the commented code below unusable anyway.
# fast but returns false positive if files remain in /etc
#[[ -f /var/lib/dpkg/info/${pkg}.list ]] || return 1
done
return 0
}
# Apt-get functions.
# apt-get update, exit if there is an error message.
# (apt-get will return 0 even if there is a warning message on stderr)
# safeUpdate --ignore 'string' to ignore certain error message
safeUpdate() {
local ignore_string=
# TODO: check if password error ignore is no longer needed
local ignore_string_pw='Sorry, try again.' # message if password mistyped
[[ ${1-} = '--ignore' ]] && {
ignore_string="${2-}"
}
local temp apt_error ret
temp=$(mktemp)
LC_MESSAGES=C sudo apt-get update 2>"$temp"
ret=$?
apt_error=$(<"$temp")
rm "$temp"
if [[ $ret = 0 ]] && {
[[ -z "$apt_error" ]] || ! grep -iqEv "(${ignore_string_pw:-$^}|${ignore_string:-$^}|^$)" <<<"$apt_error"
}
then
say 'Finished update' 1
return 0
else
errorExit 'There were problems during the update.' "$apt_error"
return 1
fi
}
# apt-get upgrade, exit if there is an error message.
# (apt-get will return 0 even if there is a warning message on stderr)
# safeUpgrade [--dist-upgrade (for dist-upgrade)] [--apt-get-option]
safeUpgrade() {
local cmd='upgrade'
[[ ${1-} = '--dist-upgrade' ]] && {
cmd='dist-upgrade'
shift
}
local ignore_string_pw='Sorry, try again.' # message if password mistyped
local ignore_string1='Extracting templates from packages: 100%' # apt sends this to stderr!
local ignore_string2='Retrieving bug reports... Done' # apt-listbugs sends this to stderr!
local ignore_string3='Parsing Found/Fixed information... Done' # apt-listbugs sends this to stderr!
local temp apt_error ret
temp=$(mktemp)
LC_MESSAGES=C sudo apt-get "$cmd" "${@}" 2>"$temp"
ret=$?
apt_error=$(<"$temp")
rm "$temp"
if [[ $ret = 0 ]] && {
[[ -z "$apt_error" ]] || ! grep -iqEv "(${ignore_string_pw:-$^}|${ignore_string1:-$^}|${ignore_string2:-$^}|${ignore_string3:-$^}|^$)" <<<"$apt_error"
}
then
say 'Finished upgrade.' 1
return 0
else
errorExit 'There were problems during the upgrade.' "${apt_error:-Upgrade Aborted}"
return 1
fi
}
# Usage safeInstall [--apt-get-option] package [package...]
safeInstall() {
local ignore_string_pw='Sorry, try again.' # message if password mistyped
local ignore_string1='Extracting templates from packages: 100%' # apt sends this to stderr!
local ignore_string2='Retrieving bug reports... Done' # apt-listbugs sends this to stderr!
local ignore_string3='Parsing Found/Fixed information... Done' # apt-listbugs sends this to stderr!
local temp apt_error ret
temp=$(mktemp)
LC_MESSAGES=C sudo apt-get install "${@}" 2>"$temp"
ret=$?
apt_error=$(<"$temp")
rm "$temp"
if [[ $ret = 0 ]] && {
[[ -z "$apt_error" ]] || ! grep -iqEv "(${ignore_string_pw:-$^}|${ignore_string1:-$^}|${ignore_string2:-$^}|${ignore_string3:-$^}|^$)" <<<"$apt_error"
}
then
say 'Installation finished sucessfully.' 1
return 0
else
errorExit "There were problems installing ${*}" "${apt_error:-Install Aborted}"
return 1
fi
}
# Usage safeRemove [--apt-get-option] package [package...]
safeRemove() {
local ignore_string_pw='Sorry, try again.' # message if password mistyped
local ignore_string1='Extracting templates from packages: 100%' # apt sends this to stderr!
local ignore_string2='Retrieving bug reports... Done' # apt-listbugs sends this to stderr!
local ignore_string3='Parsing Found/Fixed information... Done' # apt-listbugs sends this to stderr!
local apt_error
local temp apt_error ret
temp=$(mktemp)
LC_MESSAGES=C sudo apt-get remove "${@}" 2>"$temp"
ret=$?
apt_error=$(<"$temp")
rm "$temp"
if [[ $ret = 0 ]] && {
[[ -z "$apt_error" ]] || ! grep -iqEv "(${ignore_string_pw:-$^}|${ignore_string1}|${ignore_string2}|${ignore_string3}|^$)" <<<"$apt_error"
}
then
say "Successfully removed ${*}" 1
return 0
else
errorExit "There were problems removing ${*}" "${apt_error:-Remove Aborted}"
return 1
fi
}