bunch of fixes, change sy host, deploy some new stuff
[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 if [[ $- == *i* ]]; then
145 # for readline-complete.el
146 if [[ $LC_INSIDE_EMACS ]]; then
147 # all for readline-complete.el
148 stty echo
149 bind 'set horizontal-scroll-mode on'
150 bind 'set print-completions-horizontally on'
151 bind '"\C-i": self-insert'
152 else
153
154 if [[ $KONSOLE_PROFILE_NAME ]]; then
155 TERM=xterm-256color
156 fi
157
158 if [[ $TERM == alacritty && ! -e /usr/share/terminfo/a/alacritty ]]; then
159 # todo: we should try installing the alacritty terminfo if it is not found
160 # https://github.com/alacritty/alacritty/issues/2838
161 TERM=xterm-256color
162 fi
163
164 # copying from the alacritty example above,
165 if [[ $TERM == xterm-kitty ]]; then
166 if [[ ! -e /usr/share/terminfo/x/xterm-kitty ]]; then
167 TERM=xterm-256color
168 else
169 if [[ -e /a/opt/kitty/shell-integration/bash/kitty.bash ]]; then
170 KITTY_SHELL_INTEGRATION=t
171 source /a/opt/kitty/shell-integration/bash/kitty.bash
172 fi
173 fi
174 fi
175
176 # todo: not sure this works in sakura
177 #stty werase undef
178 #bind "\C-w": kill-region
179 # sakura == xterm-256color
180 # konsole == xterm
181 if [[ $TERM != xterm-kitty && $TERM == xterm* ]]; then
182 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
183 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
184 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
185 else
186 # make ctrl-backspace work. for konsole, i fixed it through
187 # /home/iank/.local/share/konsole/default.keytab
188 stty werase ^h
189 bind '"\eOc": shell-forward-word'
190 bind '"\eOd": shell-backward-word'
191 fi
192 # i cant remember why i did this, probably to free up some keys to bind
193 # to other things in bash.
194 # other than C-c and C-z, the rest defined by stty -a are, at least in
195 # gnome-terminal, overridden by bash, or disabled by the system
196 stty lnext undef stop undef start undef
197 fi
198
199 fi
200
201 export BC_LINE_LENGTH=0
202
203 # ansible option
204 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
205
206 # note, if I use a machine I dont want files readable by all users, set
207 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
208
209 # i for insensitive. the rest from
210 # X means dont remove the current screenworth of output upon exit
211 # R means to show colors n things
212 export LESS=RXij12
213 export SYSTEMD_LESS=$LESS
214
215 export NNN_COLORS=2136
216
217 export SL_FILES_DIR=/b/ds/sl/.iank
218 export SL_INFO_DIR=/p/sshinfo
219
220
221 # * include files
222
223 if [[ -s $bashrc_dir/path-add-function ]]; then
224 source $bashrc_dir/path-add-function
225 if [[ $SSH_CLIENT ]]; then
226 # [[ -d /home/iank/.iank/e/e ]] mounts it unnecessarily, so use this.
227 if grep -qF /home/iank/.iank/e/e /etc/auto.iank /etc/exports &>/dev/null; then
228 export EMACSDIR=/home/iank/.iank/e/e
229 fi
230 fi
231 fi
232
233 # if someone exported $SOE (stop on error), catch errors.
234 #
235 # Note, on debian this results in the following warning when in ssh,
236 # hich I haven't figured out how to fix. It doesn't happen if we source
237 # after the shell has started
238 #
239 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
240 # bash: warning: cannot start debugger; debugging mode disabled
241 if [[ $SOE ]]; then
242 if [[ -e /a/bin/errhandle/err ]]; then
243 source /a/bin/errhandle/err
244 fi
245 fi
246
247 # based on readme.debian. dunno if this will break on other distros.
248 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
249 source /usr/share/wcd/wcd-include.sh
250 fi
251
252 if [[ -s /a/bin/small-misc-bash/ll-function ]]; then
253 source /a/bin/small-misc-bash/ll-function
254 elif [[ -s $bashrc_dir/ll-function ]]; then
255 # shellcheck source=/a/bin/small-misc-bash/ll-function
256 source $bashrc_dir/ll-function
257 fi
258
259
260
261
262 # * functions
263 ccomp() { # copy completion
264 local src=$1
265 local c
266 shift
267 if ! c=$(complete -p $src 2>/dev/null); then
268 _completion_loader $src &>/dev/null ||:
269 c=$(complete -p $src 2>/dev/null) || return 0
270 fi
271 # remove $src( .*|$)
272 c=${c% $src}
273 c=${c%% $src *}
274 eval $c $*
275 }
276
277
278 ..() { c ..; }
279 ...() { c ../..; }
280 ....() { c ../../..; }
281 .....() { c ../../../..; }
282 ......() { c ../../../../..; }
283
284 chere() {
285 local f path
286 for f; do
287 path=$(readlink -e "$f")
288 echo "cat >$path <<'EOF'"
289 cat "$f"
290 echo EOF
291 done
292 }
293
294
295 # file cut copy and paste, like the text buffers :)
296 # I havnt tested these.
297 _fbufferinit() { # internal use
298 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
299 rm -rf "${my_f_tempdir:?}"/*
300 }
301 fcp() { # file cp
302 _fbufferinit
303 cp "$@" "$my_f_tempdir"/
304 }
305 fct() { # file cut
306 _fbufferinit
307 mv "$@" "$my_f_tempdir"/
308 }
309 fpst() { # file paste
310 [[ $2 ]] && { echo too many arguments; return 1; }
311 target=${1:-.}
312 cp "$my_f_tempdir"/* "$target"
313 }
314
315 _khfix_common() {
316 local host ip port
317 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" ||: )
318 if [[ ! $ip ]]; then
319 echo "khfix: ssh failed"
320 return 1
321 fi
322 if [[ $port != 22 ]]; then
323 ip_entry="[$ip]:$port"
324 host_entry="[$host]:$port"
325 else
326 ip_entry=$ip
327 host_entry=$host
328 fi
329 if [[ $host != $ip ]]; then
330 m ssh-keygen -R "$host_entry" -f $(readlink -f ~/.ssh/known_hosts)
331 ll ~/.ssh/known_hosts
332 fi
333 m ssh-keygen -R "$ip_entry" -f $(readlink -f ~/.ssh/known_hosts)
334 ll ~/.ssh/known_hosts
335 rootsshsync
336 }
337 khfix() { # known hosts fix
338 _khfix_common "$@" || return 1
339 ssh $1 :
340 }
341 khcopy() {
342 _khfix_common "$@"
343 ssh-copy-id $1
344 }
345
346 a() {
347 local x
348 x=$(readlink -nf "${1:-$PWD}")
349 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
350 echo -n "$x" | xclip -selection clipboard
351 echo -n "$x" | xclip
352 }
353
354 # a1 = awk {print $1}
355 for field in {1..20}; do
356 eval a$field"() { awk '{print \$$field}'; }"
357 done
358 # h1 = head -n1
359 for num in {1..9}; do
360 eval h$num"() { head -n$num; }"
361 done
362
363
364 b() {
365 # backwards
366 c -
367 }
368
369
370 # c. better cd
371 if type -p wcd &>/dev/null; then
372 if [[ $LC_INSIDE_EMACS ]]; then
373 c() { wcd -c -z 50 -o "$@"; }
374 else
375 # lets see what the fancy terminal does from time to time
376 c() { wcd -c -z 50 "$@"; }
377 fi
378 else
379 c() { cd "$@"; }
380 fi
381 ccomp cd c
382
383 c4() { c /var/log/exim4; }
384
385 caa() { git commit --amend --no-edit -a; }
386
387 cf() {
388 for f; do
389 hr
390 echo "$f"
391 hr
392 cat "$f"
393 done
394 }
395 caf() {
396 # shellcheck disable=SC2033
397 find -L "$@" -type f -not \( -name .svn -prune -o -name .git -prune \
398 -o -name .hg -prune -o -name .editor-backups -prune \
399 -o -name .undo-tree-history -prune \) \
400 -exec bash -c '. ~/.bashrc; hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
401
402 }
403 ccomp cat cf caf
404
405 calc() { echo "scale=3; $*" | bc -l; }
406 # no having to type quotes, but also no command history:
407 clc() {
408 local x
409 read -r x
410 echo "scale=3; $x" | bc -l
411 }
412
413 cam() {
414 git commit -am "$*"
415 }
416
417 ccat () { # config cat. see a config without extra lines.
418 sed -r '/^[[:space:]]*([;#]|--|\/\/|$)/d' "$@"
419 }
420 ccomp grep ccat
421
422 chrbind() {
423 local d
424 # dev/pts needed for pacman signature check
425 for d in dev proc sys dev/pts; do
426 [[ -d $d ]]
427 if ! mountpoint $d &>/dev/null; then
428 s mount -o bind /$d $d
429 fi
430 done
431 }
432
433
434 _cdiff-prep() {
435 # join options which are continued to multiples lines onto one line
436 local first=true
437 while IFS= read -r line; do
438 # remove leading spaces/tabs. assumes extglob
439 if [[ $line == "[ ]*" ]]; then
440 line="${line##+( )}"
441 fi
442 if $first; then
443 pastline="$line"
444 first=false
445 elif [[ $line == *=* ]]; then
446 echo "$pastline" >> "$2"
447 pastline="$line"
448 else
449 pastline="$pastline $line"
450 fi
451 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
452 echo "$pastline" >> "$2"
453 }
454
455 cdiff() {
456 # diff config files,
457 # setup for format of postfix, eg:
458 # option = stuff[,]
459 # [more stuff]
460 local pastline unified f1 f2
461 unified="$(mktemp)"
462 f1="$(mktemp)"
463 f2="$(mktemp)"
464 _cdiff-prep "$1" "$f1"
465 _cdiff-prep "$2" "$f2"
466 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
467 while IFS= read -r line; do
468 # the default bright red / blue doesnt work in emacs shell
469 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
470 done < "$unified"
471 }
472
473
474 cat-new-files() {
475 local start=$SECONDS
476 local dir="$1"
477 inotifywait -m "$dir" -e create -e moved_to |
478 # shellcheck disable=SC2030
479 while read -r filedir _ file; do
480 cat "$filedir$file"
481 hr
482 calc $((SECONDS - start)) / 60
483 sleep 5
484 done
485
486 }
487
488 # shellcheck disable=SC2032
489 chown() {
490 # makes it so chown -R symlink affects the symlink and its target.
491 if [[ $1 == -R ]]; then
492 shift
493 command chown -h "$@"
494 command chown -R "$@"
495 else
496 command chown "$@"
497 fi
498 }
499
500 cim() {
501 git commit -m "$*"
502 }
503
504 cl() {
505 # choose recent directory. cl = cd list
506 c =
507 }
508
509 d() { builtin bg "$@"; }
510 ccomp bg d
511
512 dc() {
513 diff --strip-trailing-cr -w "$@" # diff content
514 }
515 ccomp diff dc
516
517 despace() {
518 local x y
519 for x in "$@"; do
520 y="${x// /_}"
521 safe_rename "$x" "$y"
522 done
523 }
524
525 dig() {
526 command dig +nostats +nocmd "$@"
527 }
528 # Output with sections sorted, and removal of query id, so 2 dig outputs can be diffed.
529 digsort() {
530 local sec
531 sec=
532 dig +nordflag "$@" | sed -r 's/^(;; ->>HEADER<<-.*), id: .*/\1/' | while read -r l; do
533 if [[ $l == [^\;]* ]]; then
534 sec+="$l"$'\n'
535 else
536 if [[ $sec ]]; then
537 printf "%s" "$sec" | sort
538 sec=
539 fi
540 printf "%s\n" "$l"
541 fi
542 done
543 }
544 ccomp dig digsort
545 # compare digs to the 2 servers
546 # usage: digdiff @server1 @server2 DIG_ARGS
547 # note: only the soa master nameserver will respond with
548 # ra "recursive answer" flag. That difference is meaningless afaik.
549 digdiff() {
550 local s1 s2
551 s1=$1
552 shift
553 s2=$1
554 shift
555 digsort $s1 "$@" | tee /tmp/digdiff
556 diff -u /tmp/digdiff <(digsort $s2 "$@")
557 }
558
559 dt() {
560 date "+%A, %B %d, %r" "$@"
561 }
562 ccomp date dt
563
564 dus() { # du, sorted, default arg of
565 du -sh ${@:-*} | sort -h
566 }
567 ccomp du dus
568
569
570 e() { echo "$@"; }
571
572 # echo args
573 ea() {
574 if (( ! $# )); then
575 echo no args
576 fi
577 for arg; do
578 printf "%qEOL\n" "${arg}"
579 printf "%s" "${arg}" |& hexdump -C
580 done
581 }
582 # echo vars. print var including escapes, etc
583 ev() {
584 if (( ! $# )); then
585 echo no args
586 fi
587 for arg; do
588 printf "%qEOL\n" "${!arg}"
589 printf "%s" "${!arg}" |& hexdump -C
590 done
591 }
592
593 ediff() {
594 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
595 emacs --eval "(ediff-files \"$1\" \"$2\")"
596 }
597
598 # mail related
599 etail() {
600 tail -F /var/log/exim4/mainlog -n 200 "$@"
601 }
602 ccomp tail etail
603
604 # print exim old pids
605 eoldpids() {
606 local configtime pid piduptime now daemonpid
607 printf -v now '%(%s)T' -1
608 configtime=$(stat -c%Y /var/lib/exim4/config.autogenerated)
609 if [[ -s /run/exim4/exim.pid ]]; then
610 daemonpid=$(cat /run/exim4/exim.pid)
611 fi
612 for pid in $(pgrep -f '^/usr/sbin/exim4( |$)'); do
613 # the daemonpid gets reexeced on HUP (service reloads), keeping its same old timestamp
614 if [[ $pid == $daemonpid ]]; then
615 continue
616 fi
617 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
618 if (( configtime > now - piduptime )); then
619 echo $pid
620 fi
621 done
622 }
623
624 # exim tail but only watch lines from new pids
625 etailnew() {
626 local pid oldpids
627 for pid in $(eoldpids); do
628 oldpids+="$pid|"
629 done
630 if [[ $oldpids ]]; then
631 etail | awk '$3 !~ /^\[('"${oldpids%|}"')\]$/'
632 else
633 etail
634 fi
635 }
636 # exim watch as old pids go away
637 ewatchold() {
638 local configtime pid piduptime now
639 local -i count
640 local -a oldpids
641 count=0
642 while true; do
643 oldpids=($(eoldpids))
644 if (( ! ${#oldpids[@]} )); then
645 return
646 fi
647 # print the date every 20 iterations
648 if (( ! count % 20 )); then
649 date
650 fi
651 count+=1
652 ps -f -p "${oldpids[*]}"
653 sleep 1
654 done
655 }
656
657 eless() {
658 less /var/log/exim4/mainlog
659 }
660 ccomp less eless
661 eqcat() {
662 exiqgrep -i -o 60 | while read -r i; do
663 hlm exim -Mvc $i
664 echo
665 hlm exigrep $i /var/log/exim4/mainlog | cat ||:
666 done
667 }
668 eqrmf() {
669 exiqgrep -i | xargs exim -Mrm
670 }
671
672 econfdevnew() {
673 rm -rf /tmp/edev
674 mkdir -p /tmp/edev/etc
675 cp -ra /etc/exim4 /tmp/edev/etc
676 cp -ra /etc/alias* /tmp/edev/etc
677 find /tmp/edev/etc/exim4 -type f -execdir sed -i "s,/etc/,/tmp/edev/etc/,g" '{}' +
678 econfdev
679 }
680 econfdev() {
681 update-exim4.conf -d /tmp/edev/etc/exim4 -o /tmp/edev/e.conf
682 }
683
684
685
686 # shellcheck disable=SC2032
687 f() {
688 # cd forward
689 c +
690 }
691
692 fa() {
693 # find array. make an array of file names found by find into $x
694 # argument: find arguments
695 # return: find results in an array $x
696 while read -rd ''; do
697 x+=("$REPLY");
698 done < <(find "$@" -print0);
699 }
700
701 faf() { # find all files. use -L to follow symlinks
702 find "$@" -not \( -name .svn -prune -o -name .git -prune \
703 -o -name .hg -prune -o -name .editor-backups -prune \
704 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
705 }
706
707 # todo: id like to do maybe a daily or hourly cronjob to
708 # check that my history file size is increasing. Ive had it
709 # inexplicably truncated in the past.
710 histrm() {
711 history -n
712 history | awk -v IGNORECASE=1 '{ a=$1; sub(/^( *[^ ]+){4} */, "") }; /'"$*"'/'
713 read -p "press anything but contrl-c to delete"
714 for entry in $(history | awk -v IGNORECASE=1 '{ a=$1; sub(/^( *[^ ]+){4} */, "") }; /'"$*"'/ { print a }' | tac); do
715 history -d $entry
716 done
717 history -w
718 }
719
720 # mail related
721 frozen() {
722 rm -rf /tmp/frozen
723 sudo mailq |gr frozen|awk '{print $3}' | while read -r id; do
724 sudo exim -Mvl $id
725 echo
726 sudo exim -Mvh $id
727 echo
728 sudo exim -Mvb $id
729 echo -e '\n\n##############################\n'
730 done | tee -a /tmp/frozen
731 }
732 frozenrm() {
733 local ids=()
734 while read -r line; do
735 printf '%s\n' "$line"
736 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
737 done < <(s mailq)
738 echo "sleeping for 2 in case you change your mind"
739 sleep 2
740 sudo exim -Mrm "${ids[@]}"
741 }
742
743 funce() {
744 # like -e for functions. returns on error.
745 # at the end of the function, disable with:
746 # trap ERR
747 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
748 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
749 trap ERR
750 return' ERR
751 }
752
753 getdir () {
754 local help="Usage: getdir [--help] PATH
755 Output the directory of PATH, or just PATH if it is a directory."
756 if [[ $1 == --help ]]; then
757 echo "$help"
758 return 0
759 fi
760 if [[ $# -ne 1 ]]; then
761 echo "getdir error: expected 1 argument, got $#"
762 return 1
763 fi
764 if [[ -d $1 ]]; then
765 echo "$1"
766 else
767 local dir
768 dir="$(dirname "$1")"
769 if [[ -d $dir ]]; then
770 echo "$dir"
771 else
772 echo "getdir error: directory does not exist"
773 return 1
774 fi
775 fi
776 }
777
778 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
779 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
780 local root
781 root=$(gitroot) || return 1 # function to set gitroot
782 builtin cd "$root"
783 git symbolic-ref HEAD refs/heads/$1
784 rm .git/index
785 git clean -fdx
786 }
787
788 # shellcheck disable=SC2120
789 gitroot() {
790 local help="Usage: gitroot [--help]
791 Print the full path to the root of the current git repo
792
793 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
794 and works in older versions of git which did not have that."
795 if [[ $1 == --help ]]; then
796 echo "$help"
797 return
798 fi
799 local p
800 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
801 [[ $p != /* ]] && p=$PWD
802 echo "${p%%/.git}"
803 }
804
805 g() {
806
807 # todo: patch emacs so it will look elsewhere. this is kinda sad:
808 # https://emacs.stackexchange.com/questions/4253/how-to-start-emacs-with-a-custom-user-emacs-directory
809
810 local args gdb=false
811
812 if [[ $EMACSDIR ]]; then
813 path-add "$EMACSDIR/lib-src" "$EMACSDIR/src"
814 fi
815
816 if [[ $DISPLAY ]]; then
817 args=-n
818 fi
819
820 if (( $# == 0 )); then
821 args+=" -c"
822 fi
823 # duplicate -c, but oh well
824 if ! pgrep -u $EUID emacsclient; then
825 if (( $# == 0 )) && type -p gdb &>/dev/null; then
826 gdb=true
827 else
828 args+=" -c"
829 fi
830 fi
831 if [[ $EMACSDIR ]]; then
832 # Alter the path here, otherwise the nfs mount gets triggered on the
833 # first path lookup when emacs is not being used.
834 PATH="$EMACSDIR/lib-src:$EMACSDIR/src:$PATH" EHOME=$HOME HOME=$EMACSDIR m emacsclient -a "" $args "$@"
835 else
836 if $gdb; then
837 # due to a bug, we cant debug from the start unless we get a new gdb
838 # https://sourceware.org/bugzilla/show_bug.cgi?id=24454
839 # m gdb -ex="set follow-fork-mode child" -ex=r -ex=quit --args emacs --daemon
840 m emacsclient -a "" $args "$@"
841 sleep 1
842 cd /a/opt/emacs-$(distro-name)$(distro-num)
843 s gdb -p $(pgrep -f 'emacs --daemon') -ex c
844 cd -
845 else
846 m emacsclient -a "" $args "$@"
847 fi
848 fi
849 }
850
851 # force terminal version
852 gn() {
853 g -n "$@"
854 }
855
856 gmacs() {
857 # quit will prompt if the program crashes.
858 gdb -ex=r -ex=quit --args emacs "$@"; r;
859 }
860
861 gdkill() {
862 # kill the emacs daemon
863 pk1 emacs --daemon
864 }
865
866 gr() {
867 grep -iIP --color=auto "$@" || return $?
868 }
869 grr() { # grep recursive
870 # Don't return 1 on nonmatch because this is meant to be
871 # interactive, not in a conditional.
872 if [[ ${#@} == 1 ]]; then
873 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" . || [[ $? == 1 ]]
874 else
875 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -riIP --color=auto "$@" || [[ $? == 1 ]]
876 fi
877 }
878 ccomp grep gr grr
879
880 rg() { grr "$@"; }
881 ccomp grep rg
882
883 hr() { # horizontal row. used to break up output
884 printf "$(tput setaf 5 2>/dev/null ||:)â–ˆ$(tput sgr0 2>/dev/null||:)%.0s" $(eval echo "{1..${COLUMNS:-60}}")
885 echo
886 }
887 # highlight
888 hl() {
889 local col input_len=0
890 for arg; do
891 input_len=$((input_len + 1 + ${#arg}))
892 done
893 col=$((60 - input_len))
894 printf "\e[1;97;41m%s" "$*"
895 if (( col > 0 )); then
896 printf "\e[1;97;41m \e[0m%.0s" $(eval echo "{1..${col}}")
897 fi
898 echo
899 }
900 hlm() { hl "$*"; "$@"; }
901
902 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
903
904
905 # get latest hub and run it
906 # main command to use:
907 # hub pull-request --no-edit
908 # --no-edit means to use the first commit\'s message as the pull request message.
909 # If that fails, try doing
910 # hub pull-request --no-edit -b UPSTREAM_OWNER:branch
911 # where branch is usually master. it does the pr against your current branch.
912 #
913 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
914 # it\'s at ~/.config/hub
915 hub() {
916 local up uptar updir p
917 p=/github/hub/releases/
918 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
919 uptar=${up##*/}
920 updir=${uptar%.tgz}
921 if [[ ! -e /a/opt/$updir ]]; then
922 rm -rf /a/opt/hub-linux-amd64*
923 wget -P /a/opt $up
924 tar -C /a/opt -zxf /a/opt/$uptar
925 rm -f /a/opt/$uptar
926 fi
927 if ! which hub &>/dev/null; then
928 sudo /a/opt/$updir/install
929 fi
930
931 # save token across computers
932 if [[ ! -L ~/.config/hub ]]; then
933 if [[ -e ~/.config/hub ]]; then
934 mv ~/.config/hub /p/c/subdir_files/.config/
935 fi
936 if [[ -e /p/c/subdir_files/.config/hub ]]; then
937 conflink
938 fi
939 fi
940 command hub "$@"
941 }
942
943 i() { git "$@"; }
944 ccomp git i
945
946 ic() {
947 # fast commit all
948 git commit -am "$*"
949 }
950
951
952 ifn() {
953 # insensitive find
954 find -L . -not \( -name .svn -prune -o -name .git -prune \
955 -o -name .hg -prune -o -name .editor-backups -prune \
956 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
957 }
958
959 ifd() {
960 # insensitive find directory
961 find -L . -type d -not \( -name .svn -prune -o -name .git -prune \
962 -o -name .hg -prune -o -name .editor-backups -prune \
963 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
964 }
965
966
967 ipdrop() {
968 sudo iptables -A INPUT -s $1 -j DROP
969 }
970
971
972 istext() {
973 grep -Il "" "$@" &>/dev/null
974 }
975
976 jtail() {
977 journalctl -n 10000 -f "$@"
978 }
979 jr() { journalctl "$@" ; }
980 jrf() { journalctl -f "$@" ; }
981 jru() {
982 journalctl -u exim4 _SYSTEMD_INVOCATION_ID=$(systemctl show -p InvocationID --value $1)
983 }
984
985 l() {
986 if [[ $PWD == /[iap] ]]; then
987 command ls -A --color=auto -I lost+found "$@"
988 else
989 command ls -A --color=auto "$@"
990 fi
991 }
992
993 lcn() { locate -i "*$**"; }
994
995 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first "$@"; }
996
997 lt() { ll -tr "$@"; }
998
999 lld() { ll -d "$@"; }
1000
1001 ccomp ls l lg lt lld ll
1002
1003 # low recursively
1004 lowr() {
1005 local f dirs i a
1006 local -a all
1007 for dirs in false true; do
1008 for f; do
1009 if [[ -d $f ]]; then
1010 all=("$f"/**)
1011 # reverse the order to rename the nested dirs first.
1012 # note: 0 element is the dir itself
1013 for ((i=${#all[@]}-1; i>=1; i--)); do
1014 a="${all[i]}"
1015 if $dirs && [[ -d $a ]]; then
1016 # e dirs low "$a" # debug
1017 low "$a"
1018 elif ! $dirs && [[ ! -d $a && -e $a ]]; then
1019 # debug
1020 # e not dirs low "$a" # debug
1021 low "$a"
1022 fi
1023 done
1024 fi
1025 # just rename all the top level args on the second pass
1026 if $dirs; then
1027 # e final dirs low "$f" # debug
1028 low "$f"
1029 fi
1030 done
1031 done
1032 }
1033
1034 low() { # make filenames lowercase, remove bad chars
1035 local arg new dir f
1036 for arg; do
1037 arg="${arg%%+(/)}" # remove trailing slashes. assumes we have extglob on.
1038 dir="${arg%/*}"
1039 if (( ${#dir} == ${#arg} )); then
1040 dir=.
1041 fi
1042 f="${arg##*/}"
1043 new="${f,,}" # downcase
1044 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
1045 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1046 new="${new%"${new##*[[:alnum:]]}"}"
1047 # remove bad underscores, like __ and _._
1048 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1049 safe_rename "$dir/$f" "$dir/$new" || return 1
1050 done
1051 return 0
1052 }
1053
1054 lower() { # make first letter of filenames lowercase.
1055 local x
1056 for x in "$@"; do
1057 if [[ ${x::1} == [A-Z] ]]; then
1058 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1059 safe_rename "$x" "$y" || return 1
1060 fi
1061 done
1062 }
1063
1064
1065 k() { # history search
1066 grep -iP --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80 || [[ $? == 1 ]];
1067 }
1068 ks() { # history search
1069 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq || [[ $? == 1 ]];
1070 }
1071 ccomp grep k ks
1072
1073
1074 make-targets() {
1075 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1076 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1077 }
1078
1079 mkc() {
1080 mkdir "$1"
1081 c "$1"
1082 }
1083 ccomp mkdir mkc
1084
1085 mkct() {
1086 mkc $(mktemp -d)
1087 }
1088
1089 mkt() { # mkdir and touch file
1090 local path="$1"
1091 mkdir -p "$(dirname "$path")"
1092 touch "$path"
1093 }
1094
1095 # shellcheck disable=SC2032
1096 mkdir() { command mkdir -p "$@"; }
1097
1098 nags() {
1099 # https://github.com/HenriWahl/Nagstamon/issues/357
1100 if ! pgrep -f /usr/lib/notification-daemon/notification-daemon >/dev/null; then
1101 /usr/lib/notification-daemon/notification-daemon &
1102 fi
1103 /usr/bin/nagstamon &
1104 }
1105
1106 nmt() {
1107 s nmtui-connect "$@"
1108 }
1109
1110 nopanic() {
1111 # shellcheck disable=SC2024
1112 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1113 }
1114
1115 p8() { ping "$@" 8.8.8.8; }
1116 p6() { ping6 "$@" 2001:4860:4860::8888; }
1117
1118 pkx() { # package extract
1119 local pkg cached tmp f
1120 c $(mktemp -d)
1121 pkg=$1
1122 # shellcheck disable=SC2012
1123 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1 2>/dev/null) ||:
1124 if [[ $cached ]]; then
1125 cp $cached .
1126 else
1127 aptitude download $pkg || return 1
1128 fi
1129 tmp=(*); f=${tmp[0]} # only 1 expected
1130 ex $f
1131 rm -f $f
1132 }
1133
1134 # pgrep and kill
1135 pk1() {
1136 local pid
1137 pid=($(pgrep -f "$*"))
1138 case ${#pid[@]} in
1139 1)
1140 # shellcheck disable=SC2128
1141 {
1142 ps -F $pid
1143 m kill $pid
1144 }
1145 ;;
1146 0) echo "no pid found" ;;
1147 *)
1148 ps -F ${pid[@]}
1149 ;;
1150 esac
1151 }
1152
1153 psg () {
1154 local x y help
1155 help="Usage: psg [--help] GREP_ARGS
1156 grep ps and output in a nice format"
1157 if [[ $1 == --help ]]; then
1158 echo "$help"
1159 return
1160 fi
1161 x=$(ps -eF)
1162 # final grep is because some commands tend to have a lot of trailing spaces
1163 y=$(echo "$x" | grep -iP "$@" | grep -o '.*[^ ]') ||:
1164 if [[ $y ]]; then
1165 echo "$x" | head -n 1 || [[ $? == 141 ]]
1166 echo "$y"
1167 fi
1168 }
1169
1170 pubip() { curl -4s https://icanhazip.com; }
1171 pubip6() { curl -6s https://icanhazip.com; }
1172 whatismyip() { pubip; }
1173
1174
1175 q() { # start / launch a program in the backround and redir output to null
1176 "$@" &> /dev/null &
1177 }
1178
1179 # shellcheck disable=SC2120
1180 r() {
1181 if [[ $HISTFILE ]]; then
1182 history -a # save history
1183 fi
1184 trap ERR # this avoids a segfault
1185 exit ${1:0}
1186 # i had this redir, not sure why
1187 # exit "$@" 2>/dev/null
1188 }
1189
1190 # scp is insecure and deprecated.
1191 scp() {
1192 rsync --inplace "$@"
1193 }
1194
1195 randport() {
1196 # available high ports are 1024-65535,
1197 # but lets skip things that are more likely to be in use
1198 python3 <<'EOF'
1199 import secrets
1200 print(secrets.SystemRandom().randrange(10002,65500))
1201 EOF
1202 }
1203
1204 # reapply bashrc
1205 reb() {
1206 source ~/.bashrc
1207 }
1208
1209 rl() {
1210 readlink -f "$@"
1211 }
1212 ccomp readlink rl
1213
1214 rsd() {
1215 # rsync, root is required to keep permissions right.
1216 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1217 # --no-times --delete
1218 # basically, make an exact copy, use checksums instead of file times to be more accurate
1219 rsync -ahvic --delete "$@"
1220 }
1221 rsa() {
1222 # like rlu, but dont delete files on the target end which
1223 # do not exist on the original end.
1224 rsync -ahvic "$@"
1225 }
1226 rst() {
1227 # rl without preserving modification time.
1228 rsync -ahvic --delete --no-t "$@"
1229 }
1230 rsu() { # [OPTS] HOST PATH
1231 # eg. rlu -opts frodo /testpath
1232 # relative paths will expanded with readlink -f.
1233 opts=("${@:1:$#-2}") # 1 to last -2
1234 path="${*:$#}" # last
1235 host="${*:$#-1:1}" # last -1
1236 if [[ $path == .* ]]; then
1237 path=$(readlink -f $path)
1238 fi
1239 # rync here uses checksum instead of time so we dont mess with
1240 # unison relying on time as much. g is for group, same reason
1241 # to keep up with unison.
1242 m s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1243 }
1244 ccomp rsync rsd rsa rst rsu
1245
1246 resolvcat() {
1247 local f
1248 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1249 m s nscd -i hosts
1250 fi
1251 f=/etc/resolv.conf
1252 echo $f:; ccat $f
1253 hr; s ss -lpn 'sport = 53'
1254 if systemctl is-enabled dnsmasq &>/dev/null || [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1255 # this will fail is dnsmasq is failed
1256 hr; m ser status dnsmasq | cat || :
1257 f=/etc/dnsmasq.conf
1258 hr; echo $f:; ccat $f
1259 hr; m grr '^ *(servers-file|server) *=|^ *no-resolv *$' /etc/dnsmasq.conf /etc/dnsmasq.d
1260 f=/etc/dnsmasq-servers.conf
1261 hr; echo $f:; ccat $f
1262 fi
1263 hr
1264 echo /etc/nsswitch.conf:
1265 grep '^ *hosts:' /etc/nsswitch.conf
1266 if systemctl is-enabled systemd-resolved &>/dev/null || [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1267 hr; m ser status systemd-resolved | cat || :
1268 hr; m systemd-resolve --status | cat
1269 fi
1270
1271 }
1272 rcat() {
1273 resolvcat | less
1274 }
1275 reresolv() {
1276 if [[ $(systemctl is-active nscd ||:) != inactive ]]; then
1277 m ser stop nscd
1278 sleep .5
1279 m ser start nscd
1280 m sudo nscd -i hosts
1281 fi
1282 if [[ $(systemctl is-active dnsmasq ||:) != inactive ]]; then
1283 m sudo systemctl restart dnsmasq
1284 fi
1285 if [[ $(systemctl is-active systemd-resolved ||:) != inactive ]]; then
1286 m sudo systemctl restart systemd-resolved
1287 fi
1288 if type -P resolvectl &>/dev/null; then
1289 resolvectl flush-caches
1290 fi
1291 }
1292
1293 rmstrips() {
1294 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1295 }
1296
1297 s() {
1298 # background
1299 # I use a function because otherwise we cant use in a script,
1300 # cant assign to variable.
1301 #
1302 # note: gksudo is recommended for X apps because it does not set the
1303 # home directory to the same, and thus apps writing to ~ fuck things up
1304 # with root owned files.
1305 #
1306 if [[ $EUID != 0 || $1 == -* ]]; then
1307 # shellcheck disable=SC2034
1308 SUDOD="$PWD" command sudo -i "$@"
1309 DID_SUDO=true
1310 else
1311 "$@"
1312 fi
1313 }
1314 sb() { # sudo bash -c
1315 # use sb instead of s is for sudo redirections,
1316 # eg. sb 'echo "ok fine" > /etc/file'
1317 # shellcheck disable=SC2034
1318 local SUDOD="$PWD"
1319 sudo -i bash -c "$@"
1320 }
1321 ccomp sudo s sb
1322
1323 safe_rename() { # warn and dont rename if file exists.
1324 # mv -n exists, but it\'s silent
1325 if [[ $# != 2 ]]; then
1326 echo safe_rename error: $# args, need 2 >2
1327 return 1
1328 fi
1329 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1330 if [[ -e $2 || -L $2 ]]; then
1331 echo "Cannot rename $1 to $2 as it already exists."
1332 else
1333 mv -vi "$1" "$2"
1334 fi
1335 fi
1336 }
1337
1338
1339
1340 sd() {
1341 sudo dd status=none of="$1"
1342 }
1343
1344 ser() {
1345 if type -p systemctl &>/dev/null; then
1346 s systemctl "$@"
1347 else
1348 if (( $# >= 3 )); then
1349 echo iank: ser expected 2 or less arguments
1350 return 1
1351 fi
1352 s service $2 $1
1353 fi
1354 }
1355 seru() { systemctl --user "$@"; }
1356 # like restart, but do nothing if its not already started
1357 srestart() {
1358 local service=$1
1359 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1360 systemctl restart $service
1361 fi
1362 }
1363
1364 setini() { # set a value in a .ini style file
1365 key="$1" value="$2" section="$3" file="$4"
1366 if [[ -s $file ]]; then
1367 sed -ri -f - "$file" <<EOF
1368 # remove existing keys
1369 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1370 # add key
1371 /^\s*\[$section\]/a $key=$value
1372 # from section to eof, do nothing
1373 /^\s*\[$section\]/,\$b
1374 # on the last line, if we haven't found section yet, add section and key
1375 \$a [$section]\\
1376 $key=$value
1377 EOF
1378 else
1379 cat >"$file" <<EOF
1380 [$section]
1381 $key=$value
1382 EOF
1383 fi
1384 }
1385
1386 sgo() { # service go
1387 service=$1
1388 ser restart $service || return 1
1389 if type -p systemctl &>/dev/null; then
1390 ser enable $service
1391 fi
1392 }
1393 soff () {
1394 for service; do
1395 # ignore services that dont exist
1396 if systemctl cat $service &>/dev/null; then
1397 ser stop $service;
1398 ser disable $service
1399 fi
1400 done
1401 }
1402
1403 sgu() {
1404 systemctl list-unit-files | rg "$@"
1405 }
1406
1407
1408 sk() {
1409 # 2029: "unescaped, this expands on the client side." yes, I know how ssh works
1410 # 2164: "Use 'cd ... || exit' or 'cd ... || return' in case cd fails." i have automatic error handling
1411 # 2086: unquoted $var
1412 # 2046: unquoted $(cmd)
1413 # 2068: Double quote array expansions to avoid re-splitting elements.
1414 # 2119: Functions with optional args get bad warnings when none are passed.
1415 # 2033: too many false positives for thing that will never work, passing shell function to find.
1416 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1417 shellcheck -x -e 2029,2164,2086,2046,2068,2119,2033 "$@" || return $?
1418 # had this before. not sure what it is 2119
1419 }
1420
1421
1422 # sl: ssh, but firsh rsync our bashrc and related files to a special
1423 # directory on the remote host if needed.
1424
1425 # Some environment variables and files need to be setup for this to work
1426 # (mine are set at the beginning of this file)
1427
1428 # SL_FILES_DIR: Environment variable. Path to folder which should at
1429 # least have a .bashrc file or symlink. This dir will be rsynced to ~ on
1430 # remote hosts (top level symlinks are resolved) unless the host already
1431 # has a $SL_FILES_DIR/.bashrc. In that case, we assume it is a host you
1432 # control and sync files to separately and already has the ~/.bashrc you
1433 # want. The remote bash will also take its .inputrc config from this
1434 # folder (default of not existing is fine). Mine looks like this:
1435 # https://iankelling.org/git/?p=distro-setup;a=tree;f=sl/.iank
1436
1437 # SL_INFO_DIR: Environment variable. This folder stores info about what
1438 # we detected on the remote system and when we last synced. It will be created
1439 # if it does not exist. Sometimes you may want to forget about a
1440 # remote system, you can use sl --rsync, or the function for that slr
1441 # below.
1442
1443 # SL_TEST_CMD: Env var. Meant to be used to vary the files synced
1444 # depending on the remote host. Run this string on the remote host the
1445 # first time sl is run (or if we run slr). The result is passed to
1446 # SL_TEST_HOOK. For example,
1447 # export SL_TEST_CMD=". /etc/os-release ; echo \${VERSION//[^a-zA-Z0-9]/}"
1448
1449 # SL_TEST_HOOK: Env var. It is run as $SL_TEST_HOOK. This can set
1450 # $SL_FILES_DIR to vary the files synced.
1451
1452 # SL_RSYNC_ARGS: Env var. String of arguments passed to rsync. For
1453 # example to exclude files within a directory. Note, excluded
1454 # files wont be deleted on rsync, you can add --delete-excluded
1455 # to the rsync command if that is desired.
1456
1457 # SL_SSH_ARGS: Env var. Default arguments passed to ssh.
1458
1459 # For when ~/.bashrc is already customized on the remote server, you
1460 # might find it problematic that ~/.bashrc is sourced for ALL ssh
1461 # commands, even in scripts. This paragraph is all about that. bash
1462 # scripts dont source ~/.bashrc, but call ssh in scripts and you get
1463 # ~/.bashrc. You dont want this. .bashrc is meant for interactive shells
1464 # and if you customize it, probably has bugs from time to time. This is
1465 # bad. Here's how I fix it. I have a special condition to "return" in my
1466 # .bashrc for noninteractive ssh shells (copy that code). Then use this
1467 # function or similar that passes LC_USEBASHRC=t when sshing and I want
1468 # my bashrc. Also, I don't keep most of my bashrc in .bashrc, i source a
1469 # separate file because even if I return early on, the whole file gets
1470 # parsed which can fail if there is a syntax error.
1471 sl() {
1472 # Background on LC_USEBASHRC var (no need to read if you just want to
1473 # use this function): env variables sent across ssh are strictly
1474 # limited, but we get LC_* at least in debian based machines, so we
1475 # just make that * be something no normal program would use. Note, on
1476 # hosts that dont allow LC_* I start an inner shell with LC_USEBASHRC
1477 # set, and the inner shell also allows running a nondefault
1478 # .bashrc. This means the outer shell still ran the default .bashrc,
1479 # but that is the best we can do.
1480
1481 local now args remote dorsync haveinfo tmpa sshinfo tmp tmp2 type info_sec force_rsync \
1482 sync_dirname testcmd extra_info testbool files_sec sl_test_cmd sl_test_hook
1483 declare -a args tmpa
1484
1485 args=($SL_SSH_ARGS)
1486
1487 # ssh [-1246Antivivisectionist] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
1488 # [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-L address]
1489 # [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option]
1490 # [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] [user@]hostname
1491 # [command]
1492
1493 # ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
1494 # [-D [bind_address:]port] [-E log_file] [-e escape_char]
1495 # [-F configfile] [-I pkcs11] [-i identity_file]
1496 # [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
1497 # [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
1498 # [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
1499
1500 force_rsync=false
1501 if [[ $1 == --rsync ]]; then
1502 force_rsync=true
1503 shift
1504 fi
1505
1506 sl_test_cmd=$SL_TEST_CMD
1507 sl_test_hook=$SL_TEST_HOOK
1508 sl_rsync_args=$SL_RSYNC_ARGS
1509 while [[ $1 ]]; do
1510 case "$1" in
1511 --rsync)
1512 force_rsync=true
1513 ;;
1514 --sl-test-cmd)
1515 sl_test_cmd="$2"
1516 shift
1517 ;;
1518 --sl-test-hook)
1519 sl_test_hook="$2"
1520 shift
1521 ;;
1522 --sl-rsync-args)
1523 sl_rsync_args="$2"
1524 shift
1525 ;;
1526 *)
1527 break
1528 ;;
1529 esac
1530 shift
1531 done
1532
1533 while [[ $1 ]]; do
1534 case "$1" in
1535 # note we dont support things like -4oOption
1536 -[46AaCfGgKkMNnqsTtVvXxYy]*)
1537 args+=("$1"); shift
1538 ;;
1539 -[bcDEeFIiJLlmOopQRSWw]*)
1540 # -oOption etc is valid
1541 if (( ${#1} >= 3 )); then
1542 args+=("$1"); shift
1543 else
1544 args+=("$1" "$2"); shift 2
1545 fi
1546 ;;
1547 *)
1548 break
1549 ;;
1550 esac
1551 done
1552 remote="$1"
1553 if [[ ! $remote ]]; then
1554 echo $0: error hostname required >&2
1555 return 1
1556 fi
1557 shift
1558
1559 if [[ ! $SL_INFO_DIR ]]; then
1560 echo error: missing '$SL_INFO_DIR' env var >&2
1561 return 1
1562 fi
1563
1564 now=$(date +%s)
1565 dorsync=false
1566 haveinfo=false
1567 tmpa=($SL_INFO_DIR/???????????"$remote")
1568 sshinfo=${tmpa[0]}
1569 if [[ -e $sshinfo ]]; then
1570 if $force_rsync; then
1571 rm -f $sshinfo
1572 else
1573 haveinfo=true
1574 fi
1575 fi
1576 if $haveinfo; then
1577 tmp=${sshinfo[0]##*/}
1578 tmp2=${tmp::11}
1579 type=${tmp2: -1}
1580 extra_info=$(cat $sshinfo)
1581 else
1582 # we test for string to know ssh succeeded
1583 testbool="test -e $SL_FILES_DIR/.bashrc -a -L .bashrc -a -v LC_USEBASHRC"
1584 testcmd="if $testbool; then printf y; else printf n; fi"
1585 if ! tmp=$(LC_USEBASHRC=y command ssh "${args[@]}" "$remote" "$testcmd; $sl_test_cmd"); then
1586 echo failed sl test. doing plain ssh -v
1587 command ssh -v "${args[@]}" "$remote"
1588 fi
1589 if [[ $tmp == y* ]]; then
1590 type=a
1591 else
1592 dorsync=true
1593 type=b
1594 fi
1595 extra_info="${tmp:1}"
1596 fi
1597 if [[ $sl_test_hook ]]; then
1598 RSYNC_RSH="ssh ${args[*]}" $sl_test_hook "$extra_info" "$remote"
1599 fi
1600
1601 if $haveinfo && [[ $type == b ]]; then
1602 info_sec=${tmp::10}
1603 read files_sec _ < <(find -L $SL_FILES_DIR -printf "%T@ %p\n" | sort -nr || [[ $? == 141 || ${PIPESTATUS[0]} == 32 ]] )
1604 files_sec=${files_sec%%.*}
1605 if (( files_sec > info_sec )); then
1606 dorsync=true
1607 rm -f $sshinfo
1608 fi
1609 fi
1610
1611 sync_dirname=${SL_FILES_DIR##*/}
1612
1613 if [[ ! $SL_FILES_DIR ]]; then
1614 echo error: missing '$SL_FILES_DIR' env var >&2
1615 return 1
1616 fi
1617
1618 if $dorsync; then
1619 RSYNC_RSH="ssh ${args[*]}" m rsync -rptL --delete $sl_rsync_args $SL_FILES_DIR "$remote":
1620 fi
1621 if $dorsync || ! $haveinfo; then
1622 sshinfo=$SL_INFO_DIR/$now$type"$remote"
1623 [[ -e $SL_INFO_DIR ]] || mkdir -p $SL_INFO_DIR
1624 printf "%s\n" "$extra_info" >$sshinfo
1625 chmod 666 $sshinfo
1626 fi
1627 if [[ $type == b ]]; then
1628 if (( ${#@} )); then
1629 # Theres a couple ways to pass arguments, im not sure whats best,
1630 # but relying on bash 4.4+ escape quoting seems most reliable.
1631 command ssh "${args[@]}" "$remote" \
1632 LC_USEBASHRC=t bash -c '.\ '$sync_dirname'/.bashrc\;"\"\$@\""' bash ${@@Q}
1633 elif [[ ! -t 0 ]]; then
1634 # This case is when commands are being piped to ssh.
1635 # Normally, no bashrc gets sourced.
1636 # But, since we are doing all this, lets source it because we can.
1637 cat <(echo . $sync_dirname/.bashrc) - | command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1638 else
1639 command ssh -t "${args[@]}" "$remote" LC_USEBASHRC=t INPUTRC=$sync_dirname/.inputrc bash --rcfile $sync_dirname/.bashrc
1640 fi
1641 else
1642 if [[ -t 0 ]]; then
1643 LC_USEBASHRC=t command ssh "${args[@]}" "$remote" ${@@Q}
1644 else
1645 command ssh "${args[@]}" "$remote" LC_USEBASHRC=t bash
1646 fi
1647 fi
1648 # this function inspired from https://github.com/Russell91/sshrc
1649 }
1650
1651 slr() {
1652 sl --rsync "$@"
1653 }
1654 sss() { # ssh solo
1655 sl -oControlMaster=no -oControlPath=/ "$@"
1656 }
1657 # kill off old shared socket then ssh
1658 ssk() {
1659 m ssh -O exit "$@" || [[ $? == 255 ]]
1660 m sl "$@"
1661 }
1662 ccomp ssh sl slr sss ssk
1663 # plain ssh
1664 ssh() {
1665 if [[ $TERM == alacritty || $TERM == xterm-kitty ]]; then
1666 TERM=xterm-256color LC_USEBASHRC=t command ssh "$@"
1667 else
1668 LC_USEBASHRC=t command ssh "$@"
1669 fi
1670 }
1671
1672
1673 slog() {
1674 # log with script. timing is $1.t and script is $1.s
1675 # -l to save to ~/typescripts/
1676 # -t to add a timestamp to the filenames
1677 local logdir do_stamp arg_base
1678 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1679 logdir="/a/dt/"
1680 do_stamp=false
1681 while getopts "lt" option
1682 do
1683 case $option in
1684 l ) arg_base=$logdir ;;
1685 t ) do_stamp=true ;;
1686 esac
1687 done
1688 shift $((OPTIND - 1))
1689 arg_base+=$1
1690 [[ -e $logdir ]] || mkdir -p $logdir
1691 $do_stamp && arg_base+=$(date +%F.%T%z)
1692 script -t $arg_base.s 2> $arg_base.t
1693 }
1694 splay() { # script replay
1695 #logRoot="$HOME/typescripts/"
1696 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1697 scriptreplay "$1.t" "$1.s"
1698 }
1699
1700 sr() {
1701 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1702 if [[ $# == 0 ]]; then
1703 sudo -E bash -c -l "$(history -p '!!')"
1704 else
1705 echo this command redos last history item. no argument is accepted
1706 fi
1707 }
1708
1709 srm () {
1710 # with -ll, less secure but faster.
1711 command srm -ll "$@"
1712 }
1713
1714 srun() {
1715 scp $2 $1:/tmp
1716 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1717 }
1718
1719
1720 swap() {
1721 local tmp
1722 tmp=$(mktemp)
1723 mv $1 $tmp
1724 mv $2 $1
1725 mv $tmp $2
1726 }
1727
1728 tclock() { # terminal clock
1729 local x
1730 clear
1731 date +%l:%_M
1732 len=60
1733 # this goes to full width
1734 #len=${1:-$((COLUMNS -7))}
1735 x=1
1736 while true; do
1737 if (( x == len )); then
1738 end=true
1739 d="$(date +%l:%_M) "
1740 else
1741 end=false
1742 d=$(date +%l:%M:%_S)
1743 fi
1744 echo -en "\r"
1745 echo -n "$d"
1746 for ((i=0; i<x; i++)); do
1747 if (( i % 6 )); then
1748 echo -n _
1749 else
1750 echo -n .
1751 fi
1752 done
1753 if $end; then
1754 echo
1755 x=1
1756 else
1757 x=$((x+1))
1758 fi
1759 sleep 5
1760 done
1761 }
1762
1763
1764 te() {
1765 # test existence / exists
1766 local ret=0
1767 for x in "$@"; do
1768 [[ -e "$x" || -L "$x" ]] || ret=1
1769 done
1770 return $ret
1771 }
1772
1773 psoff() {
1774 # normally, i would just execute these commands in the function.
1775 # however, DEBUG is not inherited, so we need to run it outside a function.
1776 # And we want to run set -x afterwards to avoid spam, so we cram everything
1777 # in here, and then it will run after this function is done.
1778 PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "'
1779 }
1780 pson() {
1781 PROMPT_COMMAND=prompt-command
1782 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1783 trap 'settitle "$BASH_COMMAND"' DEBUG
1784 fi
1785 }
1786
1787 tx() { # toggle set -x, and the prompt so it doesnt spam
1788 if [[ $- == *x* ]]; then
1789 set +x
1790 pson
1791 else
1792 psoff
1793 fi
1794 }
1795
1796 psnetns() {
1797 # show all processes in the network namespace $1.
1798 # blank entries appear to be subprocesses/threads
1799 local x netns
1800 netns=$1
1801 ps -w | head -n 1
1802 sudo find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1803 while read -r l; do
1804 x=$(ps -w --no-headers -p $l);
1805 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1806 done
1807 }
1808
1809 m() { printf "%s\n" "$*"; "$@"; }
1810
1811 uptime() {
1812 if type -p uprecords &>/dev/null; then
1813 uprecords -B
1814 else
1815 command uptime
1816 fi
1817 }
1818
1819 virshrm() {
1820 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1821 }
1822
1823 vm-set-listen(){
1824 local t
1825 t=$(mktemp)
1826 local vm=$1
1827 local ip=$2
1828 sudo virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1829 sed -r "s/listen='[^']+/listen='$ip/"> $t
1830 sudo virsh undefine $vm
1831 sudo virsh define $t
1832 }
1833
1834
1835 vmshare() {
1836 vm-set-listen $1 0.0.0.0
1837 }
1838
1839
1840 vmunshare() {
1841 vm-set-listen $1 127.0.0.1
1842 }
1843
1844 myiwscan() {
1845 # find input, copy to pattern space, when we find the first field, print the copy in different order without newlines.
1846 # instead of using labels, we could just match a line and group, eg: /signal:/,{s/signal:(.*)/\1/h}
1847 sudo iw dev wls1 scan | sed -rn "
1848 s/^\Wcapability: (.*)/\1/;Ta;h;b
1849 :a;s/^\Wsignal: -([^.]+).*/\1/;Tb;H;b
1850 # padded to min width of 20
1851 :b;s/\WSSID: (.*)/\1 /;T;s/^(.{20}(.*[^ ])?) */\1/;H;g;s/(.*)\n(.*)\n(.*)/\2 \3 \1/gp;b
1852 "|sort -r
1853 }
1854
1855 # * misc stuff
1856
1857
1858 # temporary variables to test colorization
1859 # some copied from gentoo /etc/bash/bashrc,
1860 use_color=false
1861 # dircolors --print-database uses its own built-in database
1862 # instead of using /etc/DIR_COLORS. Try to use the external file
1863 # first to take advantage of user additions.
1864 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1865 match_lhs=""
1866 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1867 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1868 [[ -z ${match_lhs} ]] \
1869 && type -P dircolors >/dev/null \
1870 && match_lhs=$(dircolors --print-database)
1871 # test if our $TERM is in the TERM values in dircolor
1872 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1873
1874
1875 if ${use_color} && [[ $- == *i* ]]; then
1876
1877 term_bold="$(tput bold)"
1878 term_red="$(tput setaf 1)"
1879 term_green="$(tput setaf 2)"
1880 term_yellow="$(tput setaf 3)"
1881 term_purple="$(tput setaf 5)"
1882 term_nocolor="$(tput sgr0)" # no font attributes
1883
1884 # unused so far. commented for shellcheck
1885 # term_underl="$(tput smul)"
1886 # term_blue="$(tput setaf 4)"
1887 # term_cyan="$(tput setaf 6)"
1888
1889 fi
1890 # Try to keep environment pollution down, EPA loves us.
1891 unset safe_term match_lhs use_color
1892
1893 # * prompt
1894
1895
1896 if [[ $- == *i* ]]; then
1897
1898 # this needs to come before next ps1 stuff
1899 # this stuff needs bash 4, feb 2009,
1900 # old enough to no longer condition on $BASH_VERSION anymore
1901 shopt -s autocd
1902 shopt -s dirspell
1903 PS1='\w'
1904 if [[ $- == *i* ]] && [[ ! $LC_INSIDE_EMACS ]]; then
1905 PROMPT_DIRTRIM=2
1906 bind -m vi-command B:shell-backward-word
1907 bind -m vi-command W:shell-forward-word
1908 fi
1909
1910 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
1911 unset PROMPT_DIRTRIM
1912 PS1="\h:$PS1"
1913 fi
1914
1915 # emacs terminal has problems if this runs slowly,
1916 # so I've thrown a bunch of things at the wall to speed it up.
1917 prompt-command() {
1918 local return=$? # this MUST COME FIRST
1919 local ps_char ps_color
1920 unset IFS
1921
1922 if [[ $HISTFILE ]]; then
1923 history -a # save history
1924 fi
1925
1926 # assigned in brc2
1927 # shellcheck disable=SC1303
1928 if [[ $jr_pid ]]; then
1929 if [[ -e /proc/$jr_pid ]]; then
1930 kill $jr_pid
1931 fi
1932 unset jr_pid
1933 fi
1934
1935 case $return in
1936 0) ps_color="$term_purple"
1937 ps_char='\$'
1938 ;;
1939 1) ps_color="$term_green"
1940 ps_char="$return \\$"
1941 ;;
1942 *) ps_color="$term_yellow"
1943 ps_char="$return \\$"
1944 ;;
1945 esac
1946 if [[ ! -O . ]]; then # not owner
1947 if [[ -w . ]]; then # writable
1948 ps_color="$term_bold$term_red"
1949 else
1950 ps_color="$term_bold$term_green"
1951 fi
1952 fi
1953
1954 # faster than sourceing the file im guessing
1955 if [[ -e /dev/shm/iank-status && ! -e /tmp/quiet-status ]]; then
1956 eval $(< /dev/shm/iank-status)
1957 fi
1958 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
1959 ps_char="@ $ps_char"
1960 fi
1961 # We could test if sudo is active with sudo -nv
1962 # but then we get an email and log of lots of failed sudo commands.
1963 # We could turn those off, but seems better not to.
1964 if [[ $EUID != 0 ]] && [[ $DID_SUDO ]]; then
1965 ps_char="SUDO $ps_char"
1966 fi
1967 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
1968
1969 # set titlebar. instead, using more advanced
1970 # titelbar below
1971 #echo -ne "$_title_escape $HOSTNAME ${PWD/#$HOME/~} \007"
1972 }
1973 PROMPT_COMMAND=prompt-command
1974
1975 if [[ $TERM == screen* ]]; then
1976 _title_escape="\033]..2;"
1977 else
1978 # somme sites recommend this, i dunno what the diff is.
1979 #_title_escape="\033]30;"
1980 _title_escape="\033]0;"
1981 fi
1982
1983 settitle () {
1984 # this makes it so we show the current command if
1985 # one is running, otherwise, show nothing
1986
1987 if [[ $1 == prompt-command ]]; then
1988 return 0
1989 fi
1990 if (( ${#BASH_ARGC[@]} == 1 && BASH_SUBSHELL == 0 )); then
1991 echo -ne "$_title_escape ${PWD/#$HOME/~} "
1992 printf "%s" "$*"
1993 echo -ne "\007"
1994 fi
1995 }
1996
1997 # note, this wont work:
1998 # x=$(mktemp); cp a $x
1999 # I havnt figured out why, bigger fish to fry.
2000 #
2001 # for titlebar.
2002 # condition from the screen man page i think.
2003 # note: duplicated in tx()
2004 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2005 trap 'settitle "$BASH_COMMAND"' DEBUG
2006 else
2007 trap DEBUG
2008 fi
2009
2010 fi
2011
2012 # * stuff that makes sense to be at the end
2013
2014
2015 # best practice
2016 unset IFS
2017
2018 # shellcheck disable=SC1090
2019 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2020
2021 # I had this idea to start a bash shell which would run an initial
2022 # command passed through this env variable, then continue on
2023 # interactively. But the use case I had in mind went away.
2024 #
2025 # if [[ $MY_INIT_CMD ]]; then
2026 # "${MY_INIT_CMD[@]}"
2027 # unset MY_INIT_CMD
2028 # fi
2029
2030 # ensure no bad programs appending to this file will have an affect
2031 return 0