various fixes, a few new features
[distro-setup] / brc
1 #!/bin/bash
2 # Copyright (C) 2019 Ian Kelling
3 # SPDX-License-Identifier: AGPL-3.0-or-later
4 # this gets sourced. shebang is just for file mode detection
5
6 # Use source ~/.bashrc instead of doing bash -l when running a script
7 # so this can set extdebug and avoid the bash debugger.
8 if [[ -s /a/bin/errhandle/err ]]; then
9 source /a/bin/errhandle/err
10 elif [[ -s $bashrc_dir/err ]]; then
11 # shellcheck source=/a/bin/errhandle/err
12 source $bashrc_dir/err
13 fi
14
15 # In t8, it runs clear_console for login shells by default. I don't want
16 # my console cleared. And linux ttys get cleared without this.
17 if shopt login_shell >/dev/null && [[ -e ~/.bash_logout ]]; then
18 rm ~/.bash_logout
19 fi
20
21 # if [[ -s /usr/share/bash-completion/completions/git ]]; then
22 # source /usr/share/bash-completion/completions/git
23 # fi
24 # if [[ -s /usr/share/bash-completion/completions/gitk ]]; then
25 # source /usr/share/bash-completion/completions/gitk
26 # fi
27
28 # for testing error catching:
29 # t2() {
30 # echo t2
31 # grep sdf sdfd
32 # echo wtf
33 # }
34 # t1() {
35 # echo t1
36 # t2 a b c
37 # }
38
39 # * settings
40
41 CDPATH=.
42
43
44 # remove all aliases. aliases provided by the system tend to get in the way,
45 # for example, error happens if I try to define a function the same name as an alias
46 unalias -a
47
48 # remove gnome keyring warning messages
49 # there is probably a more proper way, but I didnt find any easily on google
50 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
51 #unset GNOME_KEYRING_CONTROL
52
53 # use extra globing features.
54 shopt -s extglob
55 # include .files when globbing, but ignore files name . and ..
56 # setting this also sets dotglob.
57 export GLOBIGNORE="*/.:*/.."
58
59 # Useful info. see man bash.
60 PS4='$LINENO+ '
61
62
63 # broken with bash_completion package. Saw a bug for this once. dont anymore.
64 # still broken in wheezy
65 # still buggered in latest stable from the web, version 2.1
66 # perhaps its fixed in newer git version, which fails to make for me
67 # this note is from 6-2014.
68 # still broken in flidas.
69 #shopt -s nullglob
70
71 # make tab on an empty line do nothing
72 shopt -s no_empty_cmd_completion
73
74 # fix spelling errors for cd, only in interactive shell
75 shopt -s cdspell
76 # append history instead of overwritting it
77 shopt -s histappend
78 # for compatibility, per gentoo/debian bashrc
79 shopt -s checkwinsize
80 # attempt to save multiline single commands as single history entries.
81 shopt -s cmdhist
82 # enable **
83 shopt -s globstar
84
85
86 # inside emacs fixes
87 if [[ $LC_INSIDE_EMACS ]]; then
88 # EMACS is used by bash on startup, but we dont need it anymore.
89 # plus I hit a bug in a makefile which inherited it
90 unset EMACS
91 export LC_INSIDE_EMACS
92 export PAGER=cat
93 export MANPAGER=cat
94 # scp completion does not work, but this doesnt fix it. todo, figure this out
95 #complete -r scp &> /dev/null
96 # todo, remote file completion fails, figure out how to turn it off
97 export NODE_DISABLE_COLORS=1
98 # This gets rid of ugly terminal escape chars in node repl
99 # sometime, Id like to have completion working in emacs shell for node
100 # the offending chars can be found in lib/readline.js,
101 # things that do like:
102 # stream.write('\x1b[' + (x + 1) + 'G');
103 # We can remove them and keep readline, for example by doing this
104 # to start a repl:
105 #!/usr/bin/env nodejs
106 # var readline = require('readline');
107 # readline.cursorTo = function(a,b,c) {};
108 # readline.clearScreenDown = function(a) {};
109 # const repl = require('repl');
110 # var replServer = repl.start('');
111 #
112 # no prompt, or else readline complete seems to be confused, based
113 # on our column being different? node probably needs to send
114 # different kind of escape sequence that is not ugly. Anyways,
115 # completion doesnt work yet even with the ugly prompt, so whatever
116 #
117 export NODE_NO_READLINE=1
118
119 fi
120
121 export SSH_CONFIG_FILE_OVERRIDE=/root/.ssh/confighome
122
123 # emacs has a different default search path than the info command. This
124 # adds the info defaults to emacs, but not the reverse, because I dun
125 # care much about the cli. The search path is only on the cli if you run
126 # "info xxx", or in emacs if you run '(info xxx)', so not that
127 # important, but might as well fix it.
128
129 # info info says this path is what was compiled, and its not documented
130 # anywhere. Through source grepping, i found it in filesys.h of the info
131 # source in trisquel flidas.
132 #
133 # Traling : means for emacs to add its own stuff on to the end.
134
135 export INFOPATH=$PATH:/usr/local/info:/usr/info:/usr/local/lib/info:/usr/lib/info:/usr/local/gnu/info:/usr/local/gnu/lib/info:/usr/gnu/info:/usr/gnu/lib/info:/opt/gnu/info:/usr/share/info:/usr/share/lib/info:/usr/local/share/info:/usr/local/share/lib/info:/usr/gnu/lib/emacs/info:/usr/local/gnu/lib/emacs/info:/usr/local/lib/emacs/info:/usr/local/emacs/info:.:
136
137 # for openwrt system that has no stty, this is easier than
138 # guarding every time i use it.
139 if ! type -p stty >/dev/null; then
140 stty() { :; }
141 fi
142
143
144 use_color=false
145 if [[ $- == *i* ]]; then
146 # for readline-complete.el
147 if [[ $LC_INSIDE_EMACS ]]; then
148 # all for readline-complete.el
149 stty echo
150 bind 'set horizontal-scroll-mode on'
151 bind 'set print-completions-horizontally on'
152 bind '"\C-i": self-insert'
153 else
154
155
156 if [[ $TERM != dumb ]] && test -t 1; then
157 use_color=true
158 fi
159
160 if [[ $KONSOLE_PROFILE_NAME ]]; then
161 TERM=xterm-256color
162 fi
163
164 if [[ $TERM == alacritty && ! -e /usr/share/terminfo/a/alacritty ]]; then
165 # todo: we should try installing the alacritty terminfo if it is not found
166 # https://github.com/alacritty/alacritty/issues/2838
167 TERM=xterm-256color
168 fi
169
170 # copying from the alacritty example above,
171 if [[ $TERM == xterm-kitty ]]; then
172 if [[ ! -e /usr/share/terminfo/x/xterm-kitty ]]; then
173 TERM=xterm-256color
174 else
175 if [[ -e /a/opt/kitty/shell-integration/bash/kitty.bash ]]; then
176 KITTY_SHELL_INTEGRATION=t
177 source /a/opt/kitty/shell-integration/bash/kitty.bash
178 fi
179 fi
180 fi
181
182 # todo: not sure this works in sakura
183 #stty werase undef
184 #bind "\C-w": kill-region
185 # sakura == xterm-256color
186 # konsole == xterm
187 if [[ $TERM != xterm-kitty && $TERM == xterm* ]]; then
188 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
189 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
190 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
191 else
192 # make ctrl-backspace work. for konsole, i fixed it through
193 # /home/iank/.local/share/konsole/default.keytab
194 stty werase ^h
195 bind '"\eOc": shell-forward-word'
196 bind '"\eOd": shell-backward-word'
197 fi
198 # i cant remember why i did this, probably to free up some keys to bind
199 # to other things in bash.
200 # other than C-c and C-z, the rest defined by stty -a are, at least in
201 # gnome-terminal, overridden by bash, or disabled by the system
202 stty lnext undef stop undef start undef
203 fi
204
205 fi
206
207 case $TERM in
208 # fixup broken backspace in chroots
209 xterm-kitty|alacritty)
210 chroot() {
211 TERM=xterm-256color command chroot "$@"
212 }
213 ;;
214 esac
215
216 export BC_LINE_LENGTH=0
217
218 # ansible option
219 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
220
221 # note, if I use a machine I dont want files readable by all users, set
222 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
223
224 # i for insensitive. the rest from
225 # X means dont remove the current screenworth of output upon exit
226 # R means to show colors n things
227 # a useful flag is -F aka --quit-if-one-screen
228 export LESS=RXij12
229 export SYSTEMD_LESS=$LESS
230
231 export NNN_COLORS=2136
232
233 export SL_FILES_DIR=/b/ds/sl/.iank
234 export SL_INFO_DIR=/p/sshinfo
235
236
237 # * include files
238
239 if [[ -s $bashrc_dir/path-add-function ]]; then
240 source $bashrc_dir/path-add-function
241 if [[ $SSH_CLIENT ]]; then
242 if grep -qF /home/iank/.iank/e/e /etc/exports &>/dev/null; then
243 export EMACSDIR=/home/iank/.iank/e/e
244 fi
245 path-add $bashrc_dir
246 fi
247 fi
248
249 # if someone exported $SOE (stop on error), catch errors.
250 #
251 # Note, on debian this results in the following warning when in ssh,
252 # hich I haven't figured out how to fix. It doesn't happen if we source
253 # after the shell has started
254 #
255 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
256 # bash: warning: cannot start debugger; debugging mode disabled
257 if [[ $SOE ]]; then
258 if [[ -e /a/bin/errhandle/err ]]; then
259 source /a/bin/errhandle/err
260 fi
261 fi
262
263
264
265
266 mysrc() {
267 local path dir file
268 path=$1
269 dir=${path%/*}
270 file=${path##*/}
271 if [[ -s $path ]]; then
272 source $path
273 elif [[ -s $bashrc_dir/$file ]]; then
274 source $bashrc_dir/$file
275 fi
276 }
277
278
279 mysrc /a/bin/small-misc-bash/ll-function
280 mysrc /a/bin/distro-functions/src/package-manager-abstractions
281
282
283 # * functions
284
285 ### begin FSF section ###
286
287 # Comments before functions are meant to be good useful
288 # documentation. If they fail at that, please improve them or send Ian a
289 # note.
290
291 ## copy bash completion
292 # Usage: ORIGINAL_COMMAND TARGET_COMMAND...
293 #
294 # It copies how the bash completion works from one command to other
295 # commands.
296 ccomp() {
297 local c src
298 src=$1
299 shift
300 if ! c=$(complete -p $src 2>/dev/null); then
301 _completion_loader $src &>/dev/null ||:
302 c=$(complete -p $src 2>/dev/null) || return 0
303 fi
304 # remove $src( .*|$)
305 c=${c% $src}
306 c=${c%% $src *}
307 eval $c $*
308 }
309
310 ## directory history tracking and navigation.
311 #
312 # cd becomes a function, also aliased to c. b to go back, f to go
313 # forward, cl to list recent directories and choose one.
314 #
315 # The finer details you may want to skip:
316 #
317 # We also define bl to print the list of back and forward directories.
318 #
319 # We keep 2 stacks, forward and back. Unlike with a web browser, the
320 # forward stack is not erased when going somewhere new.
321 #
322 # Recent directories are stored in ~/.cdirs.
323 #
324 declare -a _dir_forward _dir_back
325 c() {
326 # normally, the top of _dir_back is our current dir. if it isn't,
327 # put it on there, except we don't want to do that when we
328 # just launched a shell
329 if [[ $OLDPWD ]]; then
330 if (( ${#_dir_back[@]} == 0 )) || [[ ${_dir_back[-1]} != "$PWD" ]]; then
331 _dir_back+=("$PWD")
332 fi
333 fi
334 command cd "$@"
335 if (( ${#_dir_back[@]} == 0 )) || [[ ${_dir_back[-1]} != "$PWD" ]]; then
336 _dir_back+=("$PWD")
337 fi
338 echo "$PWD" >> ~/.cdirs
339 }
340 ccomp cd c
341
342 # back
343 b() {
344 local top_back
345 if (( ${#_dir_back[@]} == 0 )); then
346 echo "nothing left to go back to" >&2
347 return 0
348 fi
349 top_back="${_dir_back[-1]}"
350
351 if [[ $top_back == "$PWD" ]] && (( ${#_dir_back[@]} == 1 )); then
352 echo "already on last back entry" >&2
353 return 0
354 fi
355
356
357 if [[ $top_back == "$PWD" ]]; then
358 # add to dirf if not already there
359 if (( ${#_dir_forward[@]} == 0 )) || [[ ${_dir_forward[-1]} != "$top_back" ]]; then
360 _dir_forward+=("$top_back")
361 fi
362 unset "_dir_back[-1]"
363 command cd "${_dir_back[-1]}"
364 else
365 if (( ${#_dir_forward[@]} == 0 )) || [[ ${_dir_forward[-1]} != "$PWD" ]]; then
366 _dir_forward+=("$PWD")
367 fi
368 command cd "$top_back"
369 fi
370
371 # Interesting feature, not sure I want it.
372 # give us a peek at what is next in the list
373 # if (( ${#_dir_back[@]} >= 2 )); then
374 # printf "%s\n" "${_dir_back[-2]}"
375 # fi
376 #
377
378 # c/b/f Implementation notes:
379 #
380 # The top of the back is $PWD
381 # as long as the last directory change was due to c,b,or cl.
382 #
383 # Example of stack changes:
384 #
385 # a b c (d)
386 ## back
387 # a b (c)
388 # d
389 #back
390 #a (b)
391 #d c
392 #back
393 #(a)
394 #d c b
395 #forward
396 #a (b)
397 #d c
398 #
399 # a b c
400 ## back
401 # a b
402 # (c)
403 ## forward
404
405 }
406 # forward
407 f() {
408 local top_forward
409 if (( ${#_dir_forward[@]} == 0 )); then
410 echo "no forward dir left" >&2
411 return 0
412 fi
413 top_forward="${_dir_forward[-1]}"
414 unset "_dir_forward[-1]"
415 c "$top_forward"
416
417 # give us a peek at what is next in the list
418 # if (( ${#_dir_forward[@]} )); then
419 # printf "%s\n" "${_dir_forward[-1]}"
420 # fi
421 }
422 # cd list
423 cl() {
424 local i line input start
425 local -A buttondirs alines
426 local -a buttons dirs lines
427 buttons=( {a..z} {2..9} )
428 if [[ ! -s ~/.cdirs ]]; then
429 echo nothing in ~/.cdirs
430 return 0
431 fi
432
433 i=0
434
435 mapfile -t lines <~/.cdirs
436 start=$(( ${#lines[@]} - 1 ))
437
438 # we have ~33 buttons as of this writing, so lets
439 # prune down the history every once in a while.
440 if (( start > 500 )); then
441 tac ~/.cdirs | awk '!seen[$0]++' | head -n 200 | tac | sponge ~/.cdirs || [[ $? == 141 ]]
442 fi
443
444 for (( j=$start; j >= 0; j-- )); do
445 line="${lines[$j]}"
446 if [[ ! $line || ${alines[$line]} || ! -d "$line" || $line == "$PWD" || line == "$HOME" ]]; then
447 continue
448 fi
449 alines[$line]=t
450 buttondirs[${buttons[i]}]="$line"
451 printf "%s %s\n" ${buttons[i]} "$line"
452 if (( i == ${#buttons[@]} - 1 )); then
453 break
454 fi
455 i=$(( i + 1 ))
456 done
457
458 if (( i == 0 )); then
459 echo "no dirs in ~/.cdirs"
460 return 0
461 fi
462 read -r -N 1 input
463 if [[ $input != $'\n' ]]; then
464 c "${buttondirs[$input]}"
465 fi
466 }
467 # back list
468 bl() {
469 local start i j max
470 max=10
471 start=$(( ${#_dir_back[@]} - 1 ))
472
473 # cleanup possible repeating of pwd
474 if (( start >= 0 )) && [[ ${_dir_back[$start]} == "$PWD" ]]; then
475 start=$(( start - 1 ))
476 fi
477 j=1
478 if (( start >= 0 )); then
479 for (( i=$start; i >= 0 ; i-- )); do
480 printf "%s %s\n" $j ${_dir_back[i]}
481 j=$(( j + 1 ))
482 if (( j >= max )); then
483 break
484 fi
485 done
486 fi
487
488 max=10
489 start=$(( ${#_dir_forward[@]} - 1 ))
490
491 # cleanup possible repeating of pwd
492 if (( start >= 0 )) && [[ ${_dir_forward[$start]} == "$PWD" ]]; then
493 start=$(( start - 1 ))
494 fi
495 if (( start < 0 )); then
496 return 0
497 fi
498 echo --
499 j=1
500 for (( i=$start; i >= 0 ; i-- )); do
501 printf "%s %s\n" $j ${_dir_forward[i]}
502 j=$(( j + 1 ))
503 if (( j >= max )); then
504 break
505 fi
506 done
507 }
508
509 # pee do. run args as a command with output copied to syslog.
510 #
511 # Usage: pd [-t TAG] COMMAND...
512 #
513 # -t TAG Override the tag in the syslog. The default is COMMAND with
514 # any path part is removed, eg. for /bin/cat the tag is cat.
515 #
516 # You can view the log via "journalctl -t TAG"
517 pd() {
518 local tag ret
519 ret=0
520 tag=${1##*/}
521 case $1 in
522 -t) tag="$2"; shift 2 ;;
523 esac
524 echo "PWD=$PWD command: $*" | logger -t $tag
525 "$@" |& pee cat "logger -t $tag" || ret=$?
526 echo "exited with status=$ret" | pee cat "logger -t $tag"
527 # this avoids any err-catch
528 (( $ret == 0 )) || return $ret
529 }
530 ccomp time pd
531
532 # jdo = journal do. Run command as transient systemd service, tailing
533 # its output in the journal until it completes.
534 #
535 # Usage: jdo COMMAND...
536 #
537 # Compared to pd: commands recognize this is a non-interactive shell.
538 # The service is unaffected if our ssh connection dies, no need to run
539 # in screen or tmux.
540 #
541 # Note: The last few lines of any existing entries for a unit by that
542 # name will be output first, and there will be a few second delay at the
543 # start of the command, and a second or so at the end.
544 #
545 # Note: Functions and aliases obviously won't work, we resolve the
546 # command to a file.
547 #
548 # Note: requires running as root.
549 jdo() {
550 local cmd cmd_name jr_pid ret
551 ret=0
552 cmd="$1"
553 shift
554 if [[ $EUID != 0 ]]; then
555 echo "jdo: error: rerun as root"
556 return 1
557 fi
558 cmd_name=${cmd##*/}
559 if [[ $cmd != /* ]]; then
560 cmd=$(type -P "$cmd")
561 fi
562 # -q = quiet
563 journalctl -qn2 -f -u "$cmd_name" &
564 # Trial and error of time needed to avoid missing initial lines.
565 # .5 was not reliable. 1 was not reliable. 2 was not reliable
566 sleep 4
567 jr_pid=$!
568 systemd-run --unit "$cmd_name" --wait --collect "$cmd" "$@" || ret=$?
569 # The sleep lets the journal output its last line
570 # before the prompt comes up.
571 sleep .5
572 kill $jr_pid &>/dev/null ||:
573 unset jr_pid
574 fg &>/dev/null ||:
575 # this avoids any err-catch
576 (( $ret == 0 )) || return $ret
577 }
578 ccomp time jdo
579 #### end fsf section
580
581
582 ..() { c ..; }
583 ...() { c ../..; }
584 ....() { c ../../..; }
585 .....() { c ../../../..; }
586 ......() { c ../../../../..; }
587
588 chere() {
589 local f path
590 for f; do
591 path=$(readlink -e "$f")
592 echo "cat >$path <<'EOF'"
593 cat "$f"
594 echo EOF
595 done
596 }
597
598
599 # file cut copy and paste, like the text buffers :)
600 # I havnt tested these.
601 _fbufferinit() { # internal use
602 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
603 rm -rf "${my_f_tempdir:?}"/*
604 }
605 fcp() { # file cp
606 _fbufferinit
607 cp "$@" "$my_f_tempdir"/
608 }
609 fct() { # file cut
610 _fbufferinit
611 mv "$@" "$my_f_tempdir"/
612 }
613 fpst() { # file paste
614 [[ $2 ]] && { echo too many arguments; return 1; }
615 target=${1:-.}
616 cp "$my_f_tempdir"/* "$target"
617 }
618
619 _khfix_common() {
620 local host ip port file key
621 read -r host ip port < <(timeout -s 9 2 ssh -oBatchMode=yes -oControlMaster=no -oControlPath=/ -v $1 |& sed -rn "s/debug1: Connecting to ([^ ]+) \[([^\]*)] port ([0-9]+).*/\1 \2 \3/p" ||: )
622 file=$(readlink -f ~/.ssh/known_hosts)
623 if [[ ! $ip ]]; then
624 echo "khfix: ssh failed"
625 return 1
626 fi
627 if [[ $port != 22 ]]; then
628 ip_entry="[$ip]:$port"
629 host_entry="[$host]:$port"
630 else
631 ip_entry=$ip
632 host_entry=$host
633 fi
634 tmpfile=$(mktemp)
635 if [[ $host != $ip ]]; then
636 key=$(ssh-keygen -F "$host_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
637 if [[ $key ]]; then
638 grep -Fv "$key" "$file" | sponge "$file"
639 fi
640 fi
641 key=$(ssh-keygen -F "$ip_entry" -f $file | sed -r 's/^.*([^ ]+ +[^ ]+) *$/\1/')
642 if [[ $key ]]; then
643 grep -Fv "$key" "$file" | sponge "$file"
644 fi
645 ll ~/.ssh/known_hosts
646 rootsshsync
647 }
648 khfix() { # known hosts fix
649 _khfix_common "$@" || return 1
650 ssh $1 :
651 }
652 khcopy() {
653 _khfix_common "$@"
654 ssh-copy-id $1
655 }
656
657 a() {
658 local x
659 x=$(readlink -nf "${1:-$PWD}")
660 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
661 echo -n "$x" | xclip -selection clipboard
662 echo -n "$x" | xclip
663 }
664
665 # a1 = awk {print $1}
666 for field in {1..20}; do
667 eval a$field"() { awk '{print \$$field}'; }"
668 done
669 # h1 = head -n1
670 for num in {1..9}; do
671 eval h$num"() { head -n$num; }"
672 done
673
674
675 hexipv4() {
676 printf '%d.%d.%d.%d\n' $(echo $1 | sed 's/../0x& /g')
677 }
678
679 vp9() {
680 local f out outdir in
681 outdir=vp9
682 case $1 in
683 --out)
684 outdir=$2
685 shift 2
686 ;;
687 esac
688 m mkdir -p $outdir
689 for f; do
690 out=$PWD/$outdir/$f
691 in=$PWD/$f
692 m cd $(mktemp -d)
693 pwd
694 m ffmpeg -threads 0 -i $in -g 192 -vcodec libvpx-vp9 -vf scale=-1:720 -max_muxing_queue_size 9999 -b:v 750K -pass 1 -an -f null /dev/null
695 m ffmpeg -y -threads 0 -i $in -g 192 -vcodec libvpx-vp9 -vf scale=-1:720 -max_muxing_queue_size 9999 -b:v 750K -pass 2 -c:a libvorbis -qscale:a 5 $out
696 cd -
697 done
698 }
699
700 utcl() { # utc 24 hour time to local hour 24 hour time
701 echo "print( ($1 $(date +%z | sed -r 's/..$//;s/^(-?)0*/\1/')) % 24)"|python3
702 }
703
704 bwm() {
705 s bwm-ng -T avg -d
706 }
707
708
709 # for running in a fai rescue. iank specific.
710 kdrescue() {
711 d=vgata-Samsung_SSD_850_EVO_2TB_S2RLNX0J502123D
712 for f in $d vgata-Samsung_SSD_870_QVO_8TB_S5VUNG0N900656V; do
713 cryptsetup luksOpen --key-file /p /dev/$f/root crypt-$f-root
714 cryptsetup luksOpen --key-file /p /dev/$f/o crypt-$f-o
715 done
716 mount -o subvol=root_trisquelaramo /dev/mapper/crypt-$d-root /mnt
717 mount -o subvol=a /dev/mapper/crypt-$d-root /mnt/a
718 mount -o subvol=o /dev/mapper/crypt-$d-o /mnt/o
719 mount -o subvol=boot_trisquelaramo /dev/sda2 /mnt/boot
720 cd /mnt
721 chrbind
722 }
723
724
725
726
727 c4() { c /var/log/exim4; }
728
729 caa() { git commit --amend --no-edit -a; }
730
731 cf() {
732 for f; do
733 hr
734 echo "$f"
735 hr
736 cat "$f"
737 done
738 }
739 caf() {
740 # shellcheck disable=SC2033
741 find -L "$@" -type f -not \( -name .svn -prune -o -name .git -prune \
742 -o -name .hg -prune -o -name .editor-backups -prune \
743 -o -name .undo-tree-history -prune \) \
744 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
745
746 }
747 ccomp cat cf caf
748
749 calc() { echo "scale=3; $*" | bc -l; }
750 # no having to type quotes, but also no command history:
751 clc() {
752 local x
753 read -r x
754 echo "scale=3; $x" | bc -l
755 }
756
757 cam() {
758 git commit -am "$*"
759 }
760
761 ccat () { # config cat. see a config without extra lines.
762 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
763 }
764 ccomp grep ccat
765
766 chrbind() {
767 local d
768 # dev/pts needed for pacman signature check
769 for d in dev proc sys dev/pts; do
770 [[ -d $d ]]
771 if ! mountpoint $d &>/dev/null; then
772 m s mount -o bind /$d $d
773 fi
774 done
775 }
776 chumount() {
777 local d
778 # dev/pts needed for pacman signature check
779 for d in dev/pts dev proc sys; do
780 [[ -d $d ]]
781 if mountpoint $d &>/dev/null; then
782 m s umount $d
783 fi
784 done
785 }
786
787
788 _cdiff-prep() {
789 # join options which are continued to multiples lines onto one line
790 local first=true
791 while IFS= read -r line; do
792 # remove leading spaces/tabs. assumes extglob
793 if [[ $line == "[ ]*" ]]; then
794 line="${line##+( )}"
795 fi
796 if $first; then
797 pastline="$line"
798 first=false
799 elif [[ $line == *=* ]]; then
800 echo "$pastline" >> "$2"
801 pastline="$line"
802 else
803 pastline="$pastline $line"
804 fi
805 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
806 echo "$pastline" >> "$2"
807 }
808
809 cdiff() {
810 # diff config files,
811 # setup for format of postfix, eg:
812 # option = stuff[,]
813 # [more stuff]
814 local pastline unified f1 f2
815 unified="$(mktemp)"
816 f1="$(mktemp)"
817 f2="$(mktemp)"
818 _cdiff-prep "$1" "$f1"
819 _cdiff-prep "$2" "$f2"
820 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
821 while IFS= read -r line; do
822 # the default bright red / blue doesnt work in emacs shell
823 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
824 done < "$unified"
825 }
826
827
828 cat-new-files() {
829 local start=$SECONDS
830 local dir="$1"
831 # shellcheck disable=SC2030
832 inotifywait -m "$dir" -e create -e moved_to | \
833 while read -r filedir _ file; do
834 cat "$filedir$file"
835 hr
836 calc $((SECONDS - start)) / 60
837 sleep 5
838 done
839
840 }
841
842 chownme() {
843 s chown -R $USER:$USER "$@"
844 }
845
846 # shellcheck disable=SC2032
847 chown() {
848 # makes it so chown -R symlink affects the symlink and its target.
849 if [[ $1 == -R ]]; then
850 shift
851 command chown -h "$@"
852 command chown -R "$@"
853 else
854 command chown "$@"
855 fi
856 }
857
858 cim() {
859 git commit -m "$*"
860 }
861
862
863 d() { builtin bg "$@"; }
864 ccomp bg d
865
866 # f would be more natural, but i already am using it for something
867 z() { builtin fg "$@"; }
868 ccomp fg z
869
870 x() { builtin kill %%; }
871
872 dc() {
873 diff --strip-trailing-cr -w "$@" # diff content
874 }
875 ccomp diff dc
876
877 despace() {
878 local x y
879 for x in "$@"; do
880 y="${x// /_}"
881 safe_rename "$x" "$y"
882 done
883 }
884
885 # df progress
886 # usage: dfp MOUNTPOINT [SECOND_INTERVAL]
887 # SECOND_INTERVAL defaults to 90
888 dfp() {
889 # mp = mountpoint
890 local a b mp interval
891 mp=$1
892 interval=${2:-90}
893 if [[ ! $mp ]]; then
894 echo "dfp: error, missing 1st arg" >&2
895 return 1
896 fi
897 while true; do
898 a=$(df --output=used $mp | tail -n1)
899 sleep $interval
900 b=$(df --output=used $mp | tail -n1)
901 printf "used mib: %'d mib/min: %s\n" $(( b /1000 )) $(( (b-a) / (interval * 1000 / 60 ) ))
902 done
903 }
904
905 # get ipv4 ip from HOST. or if it is already a number, return that
906 hostip() {
907 local host="$1"
908 case $host in
909 [0-9:])
910 echo "$host"
911 ;;
912 *)
913 getent ahostsv4 "$host" | awk '{ print $1 }' | head -n1
914 ;;
915 esac
916 }
917
918 dig() {
919 command dig +nostats +nocmd "$@"
920 }
921 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
922 digsort() {
923 local sec
924 sec=
925 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
926 if [[ $l == [^\;]* ]]; then
927 sec+="$l"$'\n'
928 else
929 if [[ $sec ]]; then
930 printf "%s" "$sec" | sort
931 sec=
932 fi
933 printf "%s\n" "$l"
934 fi
935 done
936 }
937 ccomp dig digsort
938 # compare digs to the 2 servers
939 # usage: digdiff @server1 @server2 DIG_ARGS
940 # note: only the soa master nameserver will respond with
941 # ra "recursive answer" flag. That difference is meaningless afaik.
942 digdiff() {
943 local s1 s2
944 s1=$1
945 shift
946 s2=$1
947 shift
948 digsort $s1 "$@" | tee /tmp/digdiff
949 diff -u /tmp/digdiff <(digsort $s2 "$@")
950 }
951
952 dt() {
953 date "+%A, %B %d, %r" "$@"
954 }
955 dtr() {
956 date -R "$@"
957 }
958 ccomp date dt dtr
959
960 dus() { # du, sorted, default arg of
961 du -sh ${@:-*} | sort -h
962 }
963 ccomp du dus
964
965
966 e() { printf "%s\n" "$*"; }
967
968 # echo args
969 ea() {
970 if (( ! $# )); then
971 echo no args
972 fi
973 for arg; do
974 printf "%qEOL\n" "${arg}"
975 printf "%s" "${arg}" |& hexdump -C
976 done
977 }
978
979 # echo variables. print var including escapes, etc, like xxd for variable
980 ev() {
981 if (( ! $# )); then
982 echo no args
983 fi
984 for arg; do
985 if [[ -v $arg ]]; then
986 printf "%qEOL\n" "${!arg}"
987 printf "%s" "${!arg}" |& hexdump -C
988 else
989 echo arg $arg is unset
990 fi
991 done
992 }
993
994 ediff() {
995 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
996 emacs --eval "(ediff-files \"$1\" \"$2\")"
997 }
998
999 # mail related
1000 etail() {
1001 ngset
1002 tail -F /var/log/exim4/mainlog /var/log/exim4/*main /var/log/exim4/paniclog /var/log/exim4/*panic -n 200 "$@"
1003 ngreset
1004 }
1005 etailm() {
1006 tail -F /var/log/exim4/mainlog -n 200 "$@"
1007 }
1008 etail2() {
1009 tail -F /var/log/exim4/mymain -n 200 "$@"
1010 }
1011 ccomp tail etail etail2
1012
1013
1014 showkeys() {
1015 ssh "$@" cat .ssh/authorized_keys{,2}
1016 }
1017
1018
1019 # print exim old pids
1020 eoldpids() {
1021 local configtime pid piduptime now daemonpid
1022 printf -v now '%(%s)T' -1
1023 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
1024 if [[ -s /run/exim4/exim.pid ]]; then
1025 daemonpid=$(cat /run/exim4/exim.pid)
1026 fi
1027 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
1028 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
1029 if [[ $pid == $daemonpid ]]; then
1030 continue
1031 fi
1032 piduptime=$(awk -v ticks="$(getconf CLK_TCK)" 'NR==1 { now=$1; next } END { printf "%9.0f\n", now - ($20/ticks) }' /proc/uptime RS=')' /proc/$pid/stat) ||: # sometimes pids disappear pretty fast
1033 if (( configtime > now - piduptime )); then
1034 echo $pid
1035 fi
1036 done
1037 }
1038
1039 # exim tail but only watch lines from new pids
1040 etailnew() {
1041 local pid oldpids
1042 for pid in $(eoldpids); do
1043 oldpids+="$pid|"
1044 done
1045 if [[ $oldpids ]]; then
1046 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
1047 else
1048 etail
1049 fi
1050 }
1051 # exim watch as old pids go away
1052 ewatchold() {
1053 local configtime pid piduptime now
1054 local -i count
1055 local -a oldpids
1056 count=0
1057 while true; do
1058 oldpids=($(eoldpids))
1059 if (( ! ${#oldpids[@]} )); then
1060 return
1061 fi
1062 # print the date every 20 iterations
1063 if (( ! count % 20 )); then
1064 date
1065 fi
1066 count+=1
1067 ps -f -p "${oldpids[*]}"
1068 sleep 1
1069 done
1070 }
1071
1072 eless() {
1073 less /var/log/exim4/mainlog
1074 }
1075 ccomp less eless
1076 eqcat() {
1077 exiqgrep -ir.\* -o 60 | while read -r i; do
1078 hlm exim -Mvc $i
1079 echo
1080 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
1081 done
1082 }
1083 eqrmf() {
1084 # other ways to get the list of message ids:
1085 # exim -bp | awk 'NF == 4 {print $3}'
1086 # # this is slower 160ms, vs 60.
1087 # exipick -i
1088 exiqgrep -ir.\* | xargs exim -Mrm
1089 }
1090
1091 econfdevnew() {
1092 rm -rf /tmp/edev
1093 mkdir -p /tmp/edev/etc
1094 cp -ra /etc/exim4 /tmp/edev/etc
1095 cp -ra /etc/alias* /tmp/edev/etc
1096 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
1097 econfdev
1098 }
1099 econfdev() {
1100 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
1101 }
1102
1103
1104
1105
1106 fa() {
1107 # find array. make an array of file names found by find into $x
1108 # argument: find arguments
1109 # return: find results in an array $x
1110 while read -rd ''; do
1111 x+=("$REPLY");
1112 done < <(find "$@" -print0);
1113 }
1114
1115 faf() { # find all files. use -L to follow symlinks
1116 find "$@" -not \( -name .svn -prune -o -name .git -prune \
1117 -o -name .hg -prune -o -name .editor-backups -prune \
1118 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
1119 }
1120
1121 # usage ffconcat FILES_TO_CONCAT OUTPUT_FILE
1122 ffconcat() {
1123 local tmpf
1124 tmpf=$(mktemp)
1125 printf "file '%s'\n" "$1" >$tmpf
1126 while (( $# > 1 )); do
1127 shift
1128 printf "file '%s'\n" "$1" >>$tmpf
1129 done
1130 # https://trac.ffmpeg.org/wiki/Concatenate
1131 ffmpeg -f concat -safe 0 -i $tmpf -c copy "$1"
1132 rm $tmpf
1133 }
1134
1135 # full path without resolving symlinks
1136 fp() {
1137 local dir base
1138 base="${1##*/}"
1139 dir="${1%$base}"
1140 printf "%s/%s\n" $(cd $dir; pwd) "$base"
1141 }
1142
1143
1144 # mail related
1145 frozen() {
1146 rm -rf /tmp/frozen
1147 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
1148 sudo exim -Mvl $id
1149 echo
1150 sudo exim -Mvh $id
1151 echo
1152 sudo exim -Mvb $id
1153 echo -e '\n\n##############################\n'
1154 done | tee -a /tmp/frozen
1155 }
1156 frozenrm() {
1157 local ids=()
1158 while read -r line; do
1159 printf '%s\n' "$line"
1160 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
1161 done < <(s mailq)
1162 echo "sleeping for 2 in case you change your mind"
1163 sleep 2
1164 sudo exim -Mrm "${ids[@]}"
1165 }
1166
1167 funce() {
1168 # like -e for functions. returns on error.
1169 # at the end of the function, disable with:
1170 # trap ERR
1171 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
1172 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
1173 trap ERR
1174 return' ERR
1175 }
1176
1177 getdir () {
1178 local help="Usage: getdir [--help] PATH
1179 Output the directory of PATH, or just PATH if it is a directory."
1180 if [[ $1 == --help ]]; then
1181 echo "$help"
1182 return 0
1183 fi
1184 if [[ $# -ne 1 ]]; then
1185 echo "getdir error: expected 1 argument, got $#"
1186 return 1
1187 fi
1188 if [[ -d $1 ]]; then
1189 echo "$1"
1190 else
1191 local dir
1192 dir="$(dirname "$1")"
1193 if [[ -d $dir ]]; then
1194 echo "$dir"
1195 else
1196 echo "getdir error: directory does not exist"
1197 return 1
1198 fi
1199 fi
1200 }
1201
1202 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
1203 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
1204 local root
1205 root=$(gitroot) || return 1 # function to set gitroot
1206 builtin cd "$root"
1207 git symbolic-ref HEAD refs/heads/$1
1208 rm .git/index
1209 git clean -fdx
1210 }
1211
1212 # shellcheck disable=SC2120
1213 gitroot() {
1214 local help="Usage: gitroot [--help]
1215 Print the full path to the root of the current git repo
1216
1217 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
1218 and works in older versions of git which did not have that."
1219 if [[ $1 == --help ]]; then
1220 echo "$help"
1221 return
1222 fi
1223 local p
1224 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
1225 [[ $p != /* ]] && p=$PWD
1226 echo "${p%%/.git}"
1227 }
1228
1229 g() {
1230
1231 # todo: patch emacs so it will look elsewhere. this is kinda sad:
1232 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
1233
1234 local args gdb=false
1235
1236 if [[ $EMACSDIR ]]; then
1237 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
1238 fi
1239
1240 if [[ $DISPLAY ]]; then
1241 args=-n
1242 fi
1243
1244 if (( $# == 0 )); then
1245 args+=" -c"
1246 fi
1247 # duplicate -c, but oh well
1248 if ! pgrep -u $EUID emacsclient; then
1249 if (( $# == 0 )) && type -p gdb &>/dev/null; then
1250 gdb=true
1251 else
1252 args+=" -c"
1253 fi
1254 fi
1255 if [[ $EMACSDIR ]]; then
1256 # Alter the path here, otherwise the nfs mount gets triggered on the
1257 # first path lookup when emacs is not being used.
1258 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
1259 else
1260 if $gdb; then
1261 # due to a bug, we cant debug from the start unless we get a new gdb
1262 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
1263 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
1264 m emacsclient -a "" $args "$@"
1265 sleep 1
1266 cd /a/opt/emacs-$(distro-name)$(distro-num)
1267 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
1268 cd -
1269 else
1270 m emacsclient -a "" $args "$@"
1271 fi
1272 fi
1273 }
1274
1275 # force terminal version
1276 gn() {
1277 g -n "$@"
1278 }
1279
1280 gmacs() {
1281 # quit will prompt if the program crashes.
1282 gdb -ex=r -ex=quit --args emacs "$@"; r;
1283 }
1284
1285 gdkill() {
1286 # kill the emacs daemon
1287 pk1 emacs --daemon
1288 }
1289
1290 gr() {
1291 grep -iIP --color=auto "$@" || return $?
1292 }
1293 grr() { # grep recursive
1294 # Don't return 1 on nonmatch because this is meant to be
1295 # interactive, not in a conditional.
1296 if [[ ${#@} == 1 ]]; then
1297 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
1298 else
1299 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
1300 fi
1301 }
1302 ccomp grep gr grr
1303
1304 rg() { grr "$@"; }
1305 ccomp grep rg
1306
1307 hr() { # horizontal row. used to break up output
1308 printf "$(tput setaf 5 2>/dev/null ||:)█$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
1309 echo
1310 }
1311 # highlight
1312 hl() {
1313 local col input_len=0
1314 for arg; do
1315 input_len=$((input_len + 1 + ${#arg}))
1316 done
1317 col=$((60 - input_len))
1318 printf "\e[1;97;41m%s" "$*"
1319 if (( col > 0 )); then
1320 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
1321 fi
1322 echo
1323 }
1324 hlm() { hl "$*"; "$@"; }
1325
1326 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
1327
1328
1329 # get latest hub and run it
1330 # main command to use:
1331 # hub pull-request --no-edit
1332 # --no-edit means to use the first commit\'s message as the pull request message.
1333 # If that fails, try doing
1334 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
1335 # where branch is usually master. it does the pr against your current branch.
1336 #
1337 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1338 # it\'s at ~/.config/hub
1339 hub() {
1340 local up uptar updir p v
1341 # example https://github.com/github/hub/releases/download/v2.14.2/hub-linux-amd64-2.14.2.tgz
1342 up=$(wget -q -O- https://api.github.com/repos/github/hub/releases/latest | jq -r .assets[].browser_download_url | grep linux-amd64)
1343 re='[[:space:]]'
1344 if [[ ! $up || $up == $re ]]; then
1345 echo "failed to get good update url. got: $up"
1346 fi
1347 uptar=${up##*/}
1348 updir=${uptar%.tgz}
1349 if [[ ! -e /a/opt/$updir ]]; then
1350 rm -rf /a/opt/hub-linux-amd64*
1351 wget -P /a/opt $up
1352 tar -C /a/opt -zxf /a/opt/$uptar
1353 rm -f /a/opt/$uptar
1354 fi
1355 if ! which hub &>/dev/null; then
1356 sudo /a/opt/$updir/install
1357 fi
1358
1359 # save token across computers
1360 if [[ ! -L ~/.config/hub ]]; then
1361 if [[ -e ~/.config/hub ]]; then
1362 mv ~/.config/hub /p/c/subdir_files/.config/
1363 fi
1364 if [[ -e /p/c/subdir_files/.config/hub ]]; then
1365 conflink
1366 fi
1367 fi
1368 command hub "$@"
1369 }
1370
1371 i() { git "$@"; }
1372 ccomp git i
1373
1374 # git status:
1375 # cvs -qn update
1376
1377 # git checkout FILE
1378 # cvs update -C FILE
1379
1380 # git pull
1381 # cvs up[date]
1382
1383 # potentially useful command translation
1384 # https://fling.seas.upenn.edu/~giesen/dynamic/wordpress/equivalent-commands-for-git-svn-and-cvs/
1385
1386 # importing cvs repo into git using git-cvs package:
1387 # /f/www $ /usr/lib/git-core/git-cvsimport -C /f/www-git
1388
1389 ic() {
1390 # fast commit all
1391 git commit -am "$*"
1392 }
1393
1394 ipp() {
1395 git pull
1396 git push
1397 }
1398
1399
1400 ifn() {
1401 # insensitive find
1402 # -L = follow symlinks
1403 find -L . -not \( -name .svn -prune -o -name .git -prune \
1404 -o -name .hg -prune -o -name .editor-backups -prune \
1405 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1406 }
1407
1408 ifd() {
1409 # insensitive find directory
1410 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
1411 -o -name .hg -prune -o -name .editor-backups -prune \
1412 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1413 }
1414
1415
1416 ipdrop() {
1417 sudo iptables -A INPUT -s $1 -j DROP
1418 }
1419
1420
1421 istext() {
1422 grep -Il "" "$@" &>/dev/null
1423 }
1424
1425 pst() {
1426 pstree -apnA
1427 }
1428
1429 jtail() {
1430 journalctl -n 10000 -f "$@"
1431 }
1432 jr() { journalctl "$@" ; }
1433 jrf() { journalctl -f "$@" ; }
1434 jru() {
1435 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
1436 }
1437
1438
1439
1440 l() {
1441 if [[ $PWD == /[iap] ]]; then
1442 command ls -A --color=auto -I lost+found "$@"
1443 else
1444 command ls -A --color=auto "$@"
1445 fi
1446 }
1447
1448 lcn() { locate -i "*$**"; }
1449
1450 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
1451
1452 lt() { ll -tr "$@"; }
1453
1454 lld() { ll -d "$@"; }
1455
1456 ccomp ls l lg lt lld ll
1457
1458 # low recursively
1459 lowr() {
1460 local f dirs i a
1461 local -a all
1462 for dirs in false true; do
1463 for f; do
1464 if [[ -d $f ]]; then
1465 all=("$f"/**)
1466 # reverse the order to rename the nested dirs first.
1467 # note: 0 element is the dir itself
1468 for ((i=${#all[@]}-1; i>=1; i--)); do
1469 a="${all[i]}"
1470 if $dirs && [[ -d $a ]]; then
1471 # e dirs low "$a" # debug
1472 low "$a"
1473 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1474 # debug
1475 # e not dirs low "$a" # debug
1476 low "$a"
1477 fi
1478 done
1479 fi
1480 # just rename all the top level args on the second pass
1481 if $dirs; then
1482 # e final dirs low "$f" # debug
1483 low "$f"
1484 fi
1485 done
1486 done
1487 }
1488
1489 low() { # make filenames lowercase, remove bad chars
1490 local arg new dir f
1491 for arg; do
1492 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1493 dir="${arg%/*}"
1494 if (( ${#dir} == ${#arg} )); then
1495 dir=.
1496 fi
1497 f="${arg##*/}"
1498 new="${f,,}" # downcase
1499 new="${new//[^a-zA-Z0-9._-]/_}" # sub bad chars
1500 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1501 new="${new%"${new##*[[:alnum:]]}"}"
1502 # remove bad underscores, like __ and _._
1503 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1504 safe_rename "$dir/$f" "$dir/$new" || return 1
1505 done
1506 return 0
1507 }
1508
1509 lower() { # make first letter of filenames lowercase.
1510 local x
1511 for x in "$@"; do
1512 if [[ ${x::1} == [A-Z] ]]; then
1513 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1514 safe_rename "$x" "$y" || return 1
1515 fi
1516 done
1517 }
1518
1519
1520 k() { # history search
1521 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1522 }
1523 ks() { # history search with context
1524 # args are an extended regex used by sed
1525 history | sed -nr "h;s/^\s*(\S+\s+){4}//;/$*/{g;p}" | tail -n 80 || [[ $? == 1 ]];
1526 }
1527 ksu() { # history search unique
1528 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1529 }
1530
1531 # todo: id like to do maybe a daily or hourly cronjob to
1532 # check that my history file size is increasing. Ive had it
1533 # inexplicably truncated in the past.
1534 histrm() {
1535 history -n
1536 HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/'
1537 read -p "press anything but contrl-c to delete"
1538 for entry in $(HISTTIMEFORMAT= history | awk -v IGNORECASE=1 '{ a=$1; sub(/^ *[^ ]+ */, "") }; /'"$*"'/ { print a }' | tac); do
1539 history -d $entry
1540 done
1541 history -w
1542 }
1543
1544 ccomp grep k ks ksu histrm
1545
1546
1547 make-targets() {
1548 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1549 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1550 }
1551
1552 mkc() {
1553 mkdir "$1"
1554 c "$1"
1555 }
1556 ccomp mkdir mkc
1557
1558 mkct() {
1559 mkc $(mktemp -d)
1560 }
1561
1562 mkt() { # mkdir and touch file
1563 local path="$1"
1564 mkdir -p "$(dirname "$path")"
1565 touch "$path"
1566 }
1567
1568 # shellcheck disable=SC2032
1569 mkdir() { command mkdir -p "$@"; }
1570
1571 nags() {
1572 # https://github.com/HenriWahl/Nagstamon/issues/357
1573 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1574 /usr/lib/notification-daemon/notification-daemon &
1575 fi
1576 /usr/bin/nagstamon &
1577 }
1578
1579 nmt() {
1580 # cant use s because sudo -i doesnt work for passwordless sudo command
1581 case $EUID in
1582 0)
1583 sudo nmtui-connect "$@"
1584 ;;
1585 *)
1586 nmtui-connect "$@"
1587 ;;
1588 esac
1589 }
1590
1591
1592 ngset() {
1593 if shopt nullglob >/dev/null; then
1594 ngreset=false
1595 else
1596 shopt -s nullglob
1597 ngreset=true
1598 fi
1599 }
1600 ngreset() {
1601 if $ngreset; then
1602 shopt -u nullglob
1603 fi
1604 }
1605
1606 nopanic() {
1607 # shellcheck disable=SC2024
1608 ngset
1609 for f in /var/log/exim4/paniclog /var/log/exim4/*panic; do
1610 base=${f##*/}
1611 if [[ -s $f ]]; then
1612 echo ================== $f =============
1613 s tee -a /var/log/exim4/$base-archive <$f
1614 s truncate -s0 $f
1615 fi
1616 done
1617 ngreset
1618 }
1619
1620
1621 ping() { command ping -O "$@"; }
1622 p8() { ping "$@" 8.8.8.8; }
1623 p6() { ping6 "$@" 2001:4860:4860::8888; }
1624
1625 pkx() { # package extract
1626 local pkg cached tmp f
1627 c $(mktemp -d)
1628 pkg=$1
1629 # shellcheck disable=SC2012
1630 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1631 if [[ $cached ]]; then
1632 cp $cached .
1633 else
1634 aptitude download $pkg || return 1
1635 fi
1636 tmp=(*); f=${tmp[0]} # only 1 expected
1637 ex $f
1638 rm -f $f
1639 }
1640
1641 # pgrep and kill
1642 pk1() {
1643 local pid
1644 pid=($(pgrep -f "$*"))
1645 case ${#pid[@]} in
1646 1)
1647 # shellcheck disable=SC2128
1648 {
1649 ps -F $pid
1650 m kill $pid
1651 }
1652 ;;
1653 0) echo "no pid found" ;;
1654 *)
1655 ps -F ${pid[@]}
1656 ;;
1657 esac
1658 }
1659
1660 psg () {
1661 local x y help
1662 help="Usage: psg [--help] GREP_ARGS
1663 grep ps and output in a nice format"
1664 if [[ $1 == --help ]]; then
1665 echo "$help"
1666 return
1667 fi
1668 x=$(ps -eF)
1669 # final grep is because some commands tend to have a lot of trailing spaces
1670 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1671 if [[ $y ]]; then
1672 echo "$x" | head -n 1 || [[ $? == 141 ]]
1673 echo "$y"
1674 fi
1675 }
1676
1677 pubip() { curl -4s https://icanhazip.com; }
1678 pubip6() { curl -6s https://icanhazip.com; }
1679 whatismyip() { pubip; }
1680
1681
1682 q() { # start / launch a program in the backround and redir output to null
1683 "$@" &> /dev/null &
1684 }
1685
1686 # shellcheck disable=SC2120
1687 r() {
1688 if [[ $HISTFILE ]]; then
1689 history -a # save history
1690 fi
1691 trap ERR # this avoids a segfault
1692 exit ${1:0}
1693 # i had this redir, not sure why
1694 # exit "$@" 2>/dev/null
1695 }
1696
1697 # scp is insecure and deprecated.
1698 scp() {
1699 rsync --inplace "$@"
1700 }
1701 ccomp rsync scp
1702
1703 randport() {
1704 # available high ports are 1024-65535,
1705 # but lets skip things that are more likely to be in use
1706 python3 <<'EOF'
1707 import secrets
1708 print(secrets.SystemRandom().randrange(10002,65500))
1709 EOF
1710 }
1711
1712 # reapply bashrc
1713 reb() {
1714 source ~/.bashrc
1715 }
1716
1717 rl() {
1718 readlink -f "$@"
1719 }
1720 ccomp readlink rl
1721
1722 rsd() {
1723 # rsync, root is required to keep permissions right.
1724 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1725 # --no-times --delete
1726 # basically, make an exact copy, use checksums instead of file times to be more accurate
1727 rsync -ahvic --delete "$@"
1728 }
1729 rsa() {
1730 # like rlu, but dont delete files on the target end which
1731 # do not exist on the original end.
1732 rsync -ahvic "$@"
1733 }
1734 rst() {
1735 # rl without preserving modification time.
1736 rsync -ahvic --delete --no-t "$@"
1737 }
1738 # [RSYNC_OPTS] HOST PATH
1739 rsu() {
1740 # eg. rsu -opts frodo /testpath
1741 # relative paths will expanded with readlink -f.
1742 opts=("${@:1:$#-2}") # 1 to last -2
1743 path="${*:$#}" # last
1744 host="${*:$#-1:1}" # last -1
1745 if [[ $path == .* ]]; then
1746 path=$(readlink -f $path)
1747 fi
1748 m rsync -ahvi --relative --no-implied-dirs "${opts[@]}" "$path" "root@$host:/";
1749 }
1750 ccomp rsync rsd rsa rst rsu
1751
1752 # find programs listening on a port
1753 ssp() {
1754 local port=$1
1755 # to figure out these args, i had to look at the man page from git version, as of 2022-04.
1756 s ss -lpn state listening sport = $port
1757 }
1758
1759 resolvcat() {
1760 local f
1761 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1762 m s nscd -i hosts
1763 fi
1764 f=/etc/resolv.conf
1765 echo $f:; ccat $f
1766 hr; s ss -lpn sport = 53
1767 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1768 # this will fail is dnsmasq is failed
1769 hr; m ser status dnsmasq | cat || :
1770 f=/etc/dnsmasq.conf
1771 hr; echo $f:; ccat $f
1772 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1773 f=/etc/dnsmasq-servers.conf
1774 hr; echo $f:; ccat $f
1775 fi
1776 hr
1777 echo /etc/nsswitch.conf:
1778 grep '^ *hosts:' /etc/nsswitch.conf
1779 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1780 hr; m ser status systemd-resolved | cat || :
1781 hr; m resolvectl status | cat
1782 fi
1783
1784 }
1785 rcat() {
1786 resolvcat | less
1787 }
1788 reresolv() {
1789 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1790 m ser stop nscd
1791 sleep .5
1792 m ser start nscd
1793 m sudo nscd -i hosts
1794 fi
1795 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1796 m sudo systemctl restart dnsmasq
1797 fi
1798 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1799 m sudo systemctl restart systemd-resolved
1800 fi
1801 if type -P resolvectl &>/dev/null; then
1802 resolvectl flush-caches
1803 fi
1804 }
1805
1806 rmstrips() {
1807 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1808 }
1809
1810 urun () {
1811 umask $1
1812 shift
1813 "$@"
1814 }
1815 sudo () {
1816 command sudo "$@" || return $?
1817 DID_SUDO=true
1818 }
1819 s() {
1820 # background
1821 # I use a function because otherwise we cant use in a script,
1822 # cant assign to variable.
1823 #
1824 # note: gksudo is recommended for X apps because it does not set the
1825 # home directory to the same, and thus apps writing to ~ fuck things up
1826 # with root owned files.
1827 #
1828 if [[ $EUID != 0 || $1 == -* ]]; then
1829 # shellcheck disable=SC2034
1830 SUDOD="$PWD" command sudo -i "$@"
1831 DID_SUDO=true
1832 else
1833 "$@"
1834 fi
1835 }
1836 sb() { # sudo bash -c
1837 # use sb instead of s is for sudo redirections,
1838 # eg. sb 'echo "ok fine" > /etc/file'
1839 # shellcheck disable=SC2034
1840 local SUDOD="$PWD"
1841 sudo -i bash -c "$@"
1842 }
1843 # secret sudo
1844 se() { s urun 0077 "$@"; }
1845 ccomp sudo s sb se
1846
1847 safe_rename() { # warn and dont rename if file exists.
1848 # mv -n exists, but it\'s silent
1849 if [[ $# != 2 ]]; then
1850 echo safe_rename error: $# args, need 2 >2
1851 return 1
1852 fi
1853 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1854 if [[ -e $2 || -L $2 ]]; then
1855 echo "Cannot rename $1 to $2 as it already exists."
1856 else
1857 mv -vi "$1" "$2"
1858 fi
1859 fi
1860 }
1861
1862
1863 sd() {
1864 sudo dd status=none of="$1"
1865 }
1866
1867 ser() {
1868 if type -p systemctl &>/dev/null; then
1869 s systemctl "$@"
1870 else
1871 if (( $# >= 3 )); then
1872 echo iank: ser expected 2 or less arguments
1873 return 1
1874 fi
1875 s service $2 $1
1876 fi
1877 }
1878 serstat() {
1879 systemctl -n 40 status "$@"
1880 }
1881
1882 seru() { systemctl --user "$@"; }
1883 # like restart, but do nothing if its not already started
1884 srestart() {
1885 local service=$1
1886 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1887 systemctl restart $service
1888 fi
1889 }
1890
1891 setini() { # set a value in a .ini style file
1892 key="$1" value="$2" section="$3" file="$4"
1893 if [[ -s $file ]]; then
1894 sed -ri -f - "$file" <<EOF
1895 # remove existing keys
1896 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1897 # add key
1898 /^\s*\[$section\]/a $key=$value
1899 # from section to eof, do nothing
1900 /^\s*\[$section\]/,\$b
1901 # on the last line, if we haven't found section yet, add section and key
1902 \$a [$section]\\
1903 $key=$value
1904 EOF
1905 else
1906 cat >"$file" <<EOF
1907 [$section]
1908 $key=$value
1909 EOF
1910 fi
1911 }
1912
1913 sgo() { # service go
1914 service=$1
1915 ser restart $service || return 1
1916 if type -p systemctl &>/dev/null; then
1917 ser enable $service
1918 fi
1919 }
1920 soff () {
1921 for service; do
1922 # ignore services that dont exist
1923 if systemctl cat $service &>/dev/null; then
1924 ser stop $service;
1925 ser disable $service
1926 fi
1927 done
1928 }
1929
1930 sgu() {
1931 systemctl list-unit-files | rg "$@"
1932 }
1933
1934
1935 sk() {
1936
1937
1938 # disable a warning with:
1939 # shellcheck disable=SC2206 # reasoning
1940
1941 # see bash-template/style-guide.md for justifications
1942
1943 local quotes others
1944 quotes=2048,2068,2086,2206
1945 others=2029,2033,2054,2164
1946 shellcheck -W 999 -x -e $quotes,$others "$@" || return $?
1947 }
1948
1949
1950 # sl: ssh, but firsh rsync our bashrc and related files to a special
1951 # directory on the remote host if needed.
1952
1953 # Some environment variables and files need to be setup for this to work
1954 # (mine are set at the beginning of this file)
1955
1956 # SL_FILES_DIR: Environment variable. Path to folder which should at
1957 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1958 # remote hosts (top level symlinks are resolved) unless the host already
1959 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1960 # control and sync files to separately and already has the ~/.bashrc you
1961 # want. The remote bash will also take its .inputrc config from this
1962 # folder (default of not existing is fine). Mine looks like this:
1963 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1964
1965 # SL_INFO_DIR: Environment variable. This folder stores info about what
1966 # we detected on the remote system and when we last synced. It will be created
1967 # if it does not exist. Sometimes you may want to forget about a
1968 # remote system, you can use sl --rsync, or the function for that slr
1969 # below.
1970
1971 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1972 # depending on the remote host. Run this string on the remote host the
1973 # first time sl is run (or if we run slr). The result is passed to
1974 # SL_TEST_HOOK. For example,
1975 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1976
1977 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1978 # $SL_FILES_DIR to vary the files synced.
1979
1980 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1981 # example to exclude files within a directory. Note, excluded
1982 # files wont be deleted on rsync, you can add --delete-excluded
1983 # to the rsync command if that is desired.
1984
1985 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1986
1987 # For when ~/.bashrc is already customized on the remote server, you
1988 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1989 # commands, even in scripts. This paragraph is all about that. bash
1990 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1991 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1992 # and if you customize it, probably has bugs from time to time. This is
1993 # bad. Here's how I fix it. I have a special condition to "return" in my
1994 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1995 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1996 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1997 # separate file because even if I return early on, the whole file gets
1998 # parsed which can fail if there is a syntax error.
1999 sl() {
2000 # Background on LC_USEBASHRC var (no need to read if you just want to
2001 # use this function): env variables sent across ssh are strictly
2002 # limited, but we get LC_* at least in debian based machines, so we
2003 # just make that * be something no normal program would use. Note, on
2004 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
2005 # set, and the inner shell also allows running a nondefault
2006 # .bashrc. This means the outer shell still ran the default .bashrc,
2007 # but that is the best we can do.
2008
2009 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
2010 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
2011 declare -a args tmpa
2012
2013 args=($SL_SSH_ARGS)
2014
2015 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
2016 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
2017 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
2018 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
2019 # [command]
2020
2021 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
2022 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
2023 # [-F configfile] [-I pkcs11] [-i identity_file]
2024 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
2025 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
2026 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
2027
2028 force_rsync=false
2029 if [[ $1 == --rsync ]]; then
2030 force_rsync=true
2031 shift
2032 fi
2033
2034 sl_test_cmd=$SL_TEST_CMD
2035 sl_test_hook=$SL_TEST_HOOK
2036 sl_rsync_args=$SL_RSYNC_ARGS
2037 while [[ $1 ]]; do
2038 case "$1" in
2039 --rsync)
2040 force_rsync=true
2041 ;;
2042 --sl-test-cmd)
2043 sl_test_cmd="$2"
2044 shift
2045 ;;
2046 --sl-test-hook)
2047 sl_test_hook="$2"
2048 shift
2049 ;;
2050 --sl-rsync-args)
2051 sl_rsync_args="$2"
2052 shift
2053 ;;
2054 *)
2055 break
2056 ;;
2057 esac
2058 shift
2059 done
2060
2061 while [[ $1 ]]; do
2062 case "$1" in
2063 # note we dont support things like -4oOption
2064 -[46AaCfGgKkMNnqsTtVvXxYy]*)
2065 args+=("$1"); shift
2066 ;;
2067 -[bcDEeFIiJLlmOopQRSWw]*)
2068 # -oOption etc is valid
2069 if (( ${#1} >= 3 )); then
2070 args+=("$1"); shift
2071 else
2072 args+=("$1" "$2"); shift 2
2073 fi
2074 ;;
2075 *)
2076 break
2077 ;;
2078 esac
2079 done
2080 remote="$1"
2081 if [[ ! $remote ]]; then
2082 echo $0: error hostname required >&2
2083 return 1
2084 fi
2085 shift
2086
2087 if [[ ! $SL_INFO_DIR ]]; then
2088 echo error: missing '$SL_INFO_DIR' env var >&2
2089 return 1
2090 fi
2091
2092 dorsync=false
2093 haveinfo=false
2094 tmpa=($SL_INFO_DIR/???????????"$remote")
2095 sshinfo=${tmpa[0]}
2096 if [[ -e $sshinfo ]]; then
2097 if $force_rsync; then
2098 rm -f $sshinfo
2099 else
2100 haveinfo=true
2101 fi
2102 fi
2103 if $haveinfo; then
2104 tmp=${sshinfo[0]##*/}
2105 tmp2=${tmp::11}
2106 type=${tmp2: -1}
2107 extra_info=$(cat $sshinfo)
2108 else
2109 # we test for string to know ssh succeeded
2110 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
2111 testcmd="if $testbool; then printf y; else printf n; fi"
2112 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
2113 echo failed sl test. doing plain ssh -v
2114 command ssh -v "${args[@]}" "$remote"
2115 fi
2116 if [[ $tmp == y* ]]; then
2117 type=a
2118 else
2119 dorsync=true
2120 type=b
2121 fi
2122 extra_info="${tmp:1}"
2123 fi
2124 if [[ $sl_test_hook ]]; then
2125 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
2126 fi
2127
2128 if $haveinfo && [[ $type == b ]]; then
2129 info_sec=${tmp::10}
2130 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
2131 files_sec=${files_sec%%.*}
2132 if (( files_sec > info_sec )); then
2133 dorsync=true
2134 rm -f $sshinfo
2135 fi
2136 fi
2137
2138 sync_dirname=${SL_FILES_DIR##*/}
2139
2140 if [[ ! $SL_FILES_DIR ]]; then
2141 echo error: missing '$SL_FILES_DIR' env var >&2
2142 return 1
2143 fi
2144
2145 if $dorsync; then
2146 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
2147 fi
2148 if $dorsync || ! $haveinfo; then
2149 sshinfo=$SL_INFO_DIR/$EPOCHSECONDS$type"$remote"
2150 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
2151 printf "%s\n" "$extra_info" >$sshinfo
2152 chmod 666 $sshinfo
2153 fi
2154 if [[ $type == b ]]; then
2155 if (( ${#@} )); then
2156 # Theres a couple ways to pass arguments, im not sure whats best,
2157 # but relying on bash 4.4+ escape quoting seems most reliable.
2158 command ssh "${args[@]}" "$remote" \
2159 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
2160 elif [[ ! -t 0 ]]; then
2161 # This case is when commands are being piped to ssh.
2162 # Normally, no bashrc gets sourced.
2163 # But, since we are doing all this, lets source it because we can.
2164 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
2165 else
2166 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
2167 fi
2168 else
2169 if [[ -t 0 ]]; then
2170 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
2171 else
2172 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
2173 fi
2174 fi
2175 # this function inspired from https://github.com/Russell91/sshrc
2176 }
2177
2178 slr() {
2179 sl --rsync "$@"
2180 }
2181 sss() { # ssh solo
2182 sl -oControlMaster=no -oControlPath=/ "$@"
2183 }
2184 # kill off old shared socket then ssh
2185 ssk() {
2186 m ssh -O exit "$@" || [[ $? == 255 ]]
2187 m sl "$@"
2188 }
2189 ccomp ssh sl slr sss ssk
2190 # plain ssh
2191 ssh() {
2192 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
2193 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
2194 else
2195 LC_USEBASHRC=t command ssh "$@"
2196 fi
2197 }
2198
2199
2200 slog() {
2201 # log with script. timing is $1.t and script is $1.s
2202 # -l to save to ~/typescripts/
2203 # -t to add a timestamp to the filenames
2204 local logdir do_stamp arg_base
2205 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
2206 logdir="/a/dt/"
2207 do_stamp=false
2208 while getopts "lt" option
2209 do
2210 case $option in
2211 l ) arg_base=$logdir ;;
2212 t ) do_stamp=true ;;
2213 esac
2214 done
2215 shift $((OPTIND - 1))
2216 arg_base+=$1
2217 [[ -e $logdir ]] || mkdir -p $logdir
2218 $do_stamp && arg_base+=$(date +%F.%T%z)
2219 script -t $arg_base.s 2> $arg_base.t
2220 }
2221 splay() { # script replay
2222 #logRoot="$HOME/typescripts/"
2223 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
2224 scriptreplay "$1.t" "$1.s"
2225 }
2226
2227 sr() {
2228 # sudo redo. be aware, this command may not work right on strange distros or earlier software
2229 if [[ $# == 0 ]]; then
2230 sudo -E bash -c -l "$(history -p '!!')"
2231 else
2232 echo this command redos last history item. no argument is accepted
2233 fi
2234 }
2235
2236 srm () {
2237 # with -ll, less secure but faster.
2238 command srm -ll "$@"
2239 }
2240
2241 srun() {
2242 scp $2 $1:/tmp
2243 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
2244 }
2245
2246
2247 swap() {
2248 local tmp
2249 tmp=$(mktemp)
2250 mv $1 $tmp
2251 mv $2 $1
2252 mv $tmp $2
2253 }
2254
2255 tclock() { # terminal clock
2256 local x
2257 clear
2258 date +%l:%_M
2259 len=60
2260 # this goes to full width
2261 #len=${1:-$((COLUMNS -7))}
2262 x=1
2263 while true; do
2264 if (( x == len )); then
2265 end=true
2266 d="$(date +%l:%_M) "
2267 else
2268 end=false
2269 d=$(date +%l:%M:%_S)
2270 fi
2271 echo -en "\r"
2272 echo -n "$d"
2273 for ((i=0; i<x; i++)); do
2274 if (( i % 6 )); then
2275 echo -n _
2276 else
2277 echo -n .
2278 fi
2279 done
2280 if $end; then
2281 echo
2282 x=1
2283 else
2284 x=$((x+1))
2285 fi
2286 sleep 5
2287 done
2288 }
2289
2290
2291 te() {
2292 # test existence / exists
2293 local ret=0
2294 for x in "$@"; do
2295 [[ -e "$x" || -L "$x" ]] || ret=1
2296 done
2297 return $ret
2298 }
2299
2300 psoff() {
2301 # normally, i would just execute these commands in the function.
2302 # however, DEBUG is not inherited, so we need to run it outside a function.
2303 # And we want to run set -x afterwards to avoid spam, so we cram everything
2304 # in here, and then it will run after this function is done.
2305 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
2306 }
2307 pson() {
2308 PROMPT_COMMAND=prompt-command
2309 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2310 trap 'settitle "$BASH_COMMAND"' DEBUG
2311 fi
2312 }
2313
2314 tx() { # toggle set -x, and the prompt so it doesnt spam
2315 if [[ $- == *x* ]]; then
2316 set +x
2317 pson
2318 else
2319 psoff
2320 fi
2321 }
2322
2323 psnetns() {
2324 # show all processes in the network namespace $1.
2325 # blank entries appear to be subprocesses/threads
2326 local x netns
2327 netns=$1
2328 ps -w | head -n 1
2329 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
2330 while read -r l; do
2331 x=$(ps -w --no-headers -p $l);
2332 if [[ $x ]]; then echo "$x"; else echo $l; fi;
2333 done
2334 }
2335 nonet() {
2336 if ! s ip netns list | grep -Fx nonet &>/dev/null; then
2337 s ip netns add nonet
2338 fi
2339 sudo -E env /sbin/ip netns exec nonet sudo -E -u iank /bin/bash
2340 }
2341
2342 m() { printf "%s\n" "$*"; "$@"; }
2343
2344 # update file. note: duplicated in mail-setup
2345 u() {
2346 local tmp tmpdir dest="$1"
2347 local base="${dest##*/}"
2348 local dir="${dest%/*}"
2349 if [[ $dir != "$base" ]]; then
2350 # dest has a directory component
2351 mkdir -p "$dir"
2352 fi
2353 ur=false # u result
2354 tmpdir=$(mktemp -d)
2355 cat >$tmpdir/"$base"
2356 tmp=$(rsync -ic $tmpdir/"$base" "$dest")
2357 if [[ $tmp ]]; then
2358 printf "%s\n" "$tmp"
2359 ur=true
2360 if [[ $dest == /etc/systemd/system/* ]]; then
2361 reload=true
2362 fi
2363 fi
2364 rm -rf $tmpdir
2365 }
2366
2367
2368 uptime() {
2369 if type -p uprecords &>/dev/null; then
2370 uprecords -B
2371 else
2372 command uptime
2373 fi
2374 }
2375
2376 virshrm() {
2377 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
2378 }
2379
2380 vm-set-listen(){
2381 local t
2382 t=$(mktemp)
2383 local vm=$1
2384 local ip=$2
2385 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2386 sed -r "s/listen='[^']+/listen='$ip/"> $t
2387 sudo virsh undefine $vm
2388 sudo virsh define $t
2389 }
2390
2391
2392 vmshare() {
2393 vm-set-listen $1 0.0.0.0
2394 }
2395
2396
2397 vmunshare() {
2398 vm-set-listen $1 127.0.0.1
2399 }
2400
2401 myiwscan() {
2402 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
2403 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
2404 sudo iw dev wls1 scan | sed -rn "
2405 s/^\Wcapability: (.*)/\1/;Ta;h;b
2406 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
2407 # padded to min width of 20
2408 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
2409 "|sort -r
2410 }
2411
2412 # Run script by copying it to a temporary location first,
2413 # and changing directory, so we don't have any open
2414 # directories or files that could cause problems when
2415 # remounting.
2416 zr() {
2417 local tmp
2418 tmp=$(type -p "$1")
2419 if [[ $tmp ]]; then
2420 cd $(mktemp -d)
2421 cp -a "$tmp" .
2422 shift
2423 ./"${tmp##*/}" "$@"
2424 else
2425 "$@"
2426 fi
2427 }
2428
2429
2430 # * spark
2431 # spark 1 5 22 13 53
2432 # # => ▁▁▃▂▇
2433
2434 # The MIT License
2435 # Copyright (c) Zach Holman, https://zachholman.com
2436 # https://github.com/holman/spark
2437
2438 # As of 2022-10-28, I reviewed github forks that had several newer
2439 # commits, none had anything interesting. I did a little refactoring
2440 # mostly to fix emacs indent bug.
2441
2442 # Generates sparklines.
2443 _spark_echo()
2444 {
2445 if [ "X$1" = "X-n" ]; then
2446 shift
2447 printf "%s" "$*"
2448 else
2449 printf "%s\n" "$*"
2450 fi
2451 }
2452
2453
2454 spark()
2455 {
2456 local f tc
2457 local n numbers=
2458
2459 # find min/max values
2460 local min=0xffffffff max=0
2461
2462 for n in ${@//,/ }
2463 do
2464 # on Linux (or with bash4) we could use `printf %.0f $n` here to
2465 # round the number but that doesn't work on OS X (bash3) nor does
2466 # `awk '{printf "%.0f",$1}' <<< $n` work, so just cut it off
2467 n=${n%.*}
2468 (( n < min )) && min=$n
2469 (( n > max )) && max=$n
2470 numbers=$numbers${numbers:+ }$n
2471 done
2472
2473 # print ticks
2474 local ticks=(▁ ▂ ▃ ▄ ▅ ▆ ▇ █)
2475
2476 # use a high tick if data is constant
2477 (( min == max )) && ticks=(▅ ▆)
2478
2479 tc=${#ticks[@]}
2480 f=$(( ( (max-min) <<8)/( tc - 1) ))
2481 (( f < 1 )) && f=1
2482
2483 for n in $numbers
2484 do
2485 _spark_echo -n ${ticks[$(( ((($n-$min)<<8)/$f) ))]}
2486 done
2487 _spark_echo
2488 }
2489
2490
2491 # * misc stuff
2492
2493
2494 if $use_color && type -p tput &>/dev/null; then
2495 term_bold="$(tput bold)"
2496 term_red="$(tput setaf 1)"
2497 term_green="$(tput setaf 2)"
2498 term_yellow="$(tput setaf 3)"
2499 term_purple="$(tput setaf 5)"
2500 term_nocolor="$(tput sgr0)" # no font attributes
2501
2502 # unused so far. commented for shellcheck
2503 # term_underl="$(tput smul)"
2504 # term_blue="$(tput setaf 4)"
2505 # term_cyan="$(tput setaf 6)"
2506 fi
2507 # Try to keep environment pollution down, EPA loves us.
2508 unset safe_term match_lhs use_color
2509
2510 # * prompt
2511
2512
2513 if [[ $- == *i* ]]; then
2514
2515
2516 case $HOSTNAME in
2517 bk|je|li)
2518 if [[ $EUID == 1000 ]]; then
2519 system-status _ ||:
2520 fi
2521 ;;
2522 esac
2523
2524
2525 # this needs to come before next ps1 stuff
2526 # this stuff needs bash 4, feb 2009,
2527 # old enough to no longer condition on $BASH_VERSION anymore
2528 shopt -s autocd
2529 shopt -s dirspell
2530 PS1='\w'
2531 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
2532 PROMPT_DIRTRIM=2
2533 bind -m vi-command B:shell-backward-word
2534 bind -m vi-command W:shell-forward-word
2535 fi
2536
2537 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2538 unset PROMPT_DIRTRIM
2539 PS1="\h:$PS1"
2540 fi
2541
2542 # emacs terminal has problems if this runs slowly,
2543 # so I've thrown a bunch of things at the wall to speed it up.
2544 prompt-command() {
2545 local return=$? # this MUST COME FIRST
2546 local ps_char ps_color
2547 unset IFS
2548
2549 if [[ $HISTFILE ]]; then
2550 history -a # save history
2551 fi
2552
2553 case $return in
2554 0) ps_color="$term_purple"
2555 ps_char='\$'
2556 ;;
2557 *) ps_color="$term_green"
2558 ps_char="$return \\$"
2559 ;;
2560 esac
2561 if [[ ! -O . ]]; then # not owner
2562 if [[ -w . ]]; then # writable
2563 ps_color="$term_bold$term_red"
2564 else
2565 ps_color="$term_bold$term_green"
2566 fi
2567 fi
2568
2569 # faster than sourceing the file im guessing
2570 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
2571 eval $(< /dev/shm/iank-status)
2572 fi
2573 if [[ $MAIL_HOST && $MAIL_HOST != "$HOSTNAME" ]]; then
2574 ps_char="@ $ps_char"
2575 fi
2576 jobs_char=
2577 if [[ $(jobs -p) ]]; then
2578 jobs_char='\j '
2579 fi
2580 # We could test if sudo is active with sudo -nv
2581 # but then we get an email and log of lots of failed sudo commands.
2582 # We could turn those off, but seems better not to.
2583 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
2584 psudo="\[$term_bold$term_red\]s\[$term_nocolor\] "
2585 fi
2586 if [[ ! $HISTFILE ]]; then
2587 ps_char="NOHIST $ps_char"
2588 fi
2589 PS1="${PS1%"${PS1#*[wW]}"} $jobs_char$psudo\[$ps_color\]$ps_char\[$term_nocolor\] "
2590
2591 # set titlebar. instead, using more advanced
2592 # titelbar below
2593 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
2594 }
2595 PROMPT_COMMAND=prompt-command
2596
2597 if [[ $TERM == screen* ]]; then
2598 _title_escape="\033]..2;"
2599 else
2600 # somme sites recommend this, i dunno what the diff is.
2601 #_title_escape="\033]30;"
2602 _title_escape="\033]0;"
2603 fi
2604
2605 # make the titlebar be the last command and the current directory.
2606 settitle () {
2607
2608
2609 # These are some checks to help ensure we dont set the title at
2610 # times that the debug trap is running other than the case we
2611 # want. Some of them might not be needed.
2612 if (( ${#FUNCNAME[@]} != 1 || ${#BASH_ARGC[@]} != 2 || $BASH_SUBSHELL != 0 )); then
2613 return 0
2614 fi
2615 if [[ $1 == prompt-command ]]; then
2616 return 0
2617 fi
2618 echo -ne "$_title_escape ${PWD/#$HOME/~} "
2619 printf "%s" "$*"
2620 echo -ne "\007"
2621 }
2622
2623 # note, this wont work:
2624 # x=$(mktemp); cp a $x
2625 # I havnt figured out why, bigger fish to fry.
2626 #
2627 # for titlebar.
2628 # condition from the screen man page i think.
2629 # note: duplicated in tx()
2630 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2631 trap 'settitle "$BASH_COMMAND"' DEBUG
2632 else
2633 trap DEBUG
2634 fi
2635
2636 fi
2637
2638 # * stuff that makes sense to be at the end
2639
2640
2641 # best practice
2642 unset IFS
2643
2644 # shellcheck disable=SC1090
2645 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2646
2647 # I had this idea to start a bash shell which would run an initial
2648 # command passed through this env variable, then continue on
2649 # interactively. But the use case I had in mind went away.
2650 #
2651 # if [[ $MY_INIT_CMD ]]; then
2652 # "${MY_INIT_CMD[@]}"
2653 # unset MY_INIT_CMD
2654 # fi
2655
2656 # ensure no bad programs appending to this file will have an affect
2657 return 0