minor fixes
[distro-setup] / brc
1 #!/bin/bash
2 # this gets sourced. shebang is just for file mode detection
3
4 # note, to catch errors in functions but not outside, do:
5 # set -E -o pipefail
6 # trap return ERR
7 # trap 'trap ERR' RETURN
8
9
10 # * settings
11
12 CDPATH=.
13
14 set -o pipefail
15
16 # remove all aliases. aliases provided by the system tend to get in the way,
17 # for example, error happens if I try to define a function the same name as an alias
18 unalias -a
19
20 # remove gnome keyring warning messages
21 # there is probably a more proper way, but I didnt find any easily on google
22 # now using xfce+xmonad instead of vanilla xmonad, so disabling this
23 #unset GNOME_KEYRING_CONTROL
24
25 # use extra globing features.
26 shopt -s extglob
27 # include .files when globbing, but ignore files name . and ..
28 # setting this also sets dotglob.
29 export GLOBIGNORE="*/.:*/.."
30
31 # broken with bash_completion package. Saw a bug for this once. dont anymore.
32 # still broken in wheezy
33 # still buggered in latest stable from the web, version 2.1
34 # perhaps its fixed in newer git version, which fails to make for me
35 # this note is from 6-2014.
36 # Also, enabling this before sourcing .bashrc makes PATH be empty.
37 #shopt -s nullglob
38
39 # make tab on an empty line do nothing
40 shopt -s no_empty_cmd_completion
41
42 # advanced completion
43 # http://bash-completion.alioth.debian.org/
44 # might be sourced by the system already, but ive noticed it not being sourced before
45 if ! type _init_completion &> /dev/null && [[ -r "/usr/share/bash-completion/bash_completion" ]]; then
46 . /usr/share/bash-completion/bash_completion
47 fi
48
49
50 # fix spelling errors for cd, only in interactive shell
51 shopt -s cdspell
52 # append history instead of overwritting it
53 shopt -s histappend
54 # for compatibility, per gentoo/debian bashrc
55 shopt -s checkwinsize
56 # attempt to save multiline single commands as single history entries.
57 shopt -s cmdhist
58 # enable **
59 shopt -s globstar
60
61
62 # inside emacs fixes
63 if [[ $RLC_INSIDE_EMACS ]]; then
64 # EMACS is used by bash on startup, but we dont need it anymore.
65 # plus I hit a bug in a makefile which inherited it
66 unset EMACS
67 export RLC_INSIDE_EMACS
68 export PAGER=cat
69 export MANPAGER=cat
70 # scp completion does not work, but this doesnt fix it. todo, figure this out
71 complete -r scp &> /dev/null
72 # todo, remote file completion fails, figure out how to turn it off
73 export NODE_DISABLE_COLORS=1
74 # This gets rid of ugly terminal escape chars in node repl
75 # sometime, Id like to have completion working in emacs shell for node
76 # the offending chars can be found in lib/readline.js,
77 # things that do like:
78 # stream.write('\x1b[' + (x + 1) + 'G');
79 # We can remove them and keep readline, for example by doing this
80 # to start a repl:
81 #!/usr/bin/env nodejs
82 # var readline = require('readline');
83 # readline.cursorTo = function(a,b,c) {};
84 # readline.clearScreenDown = function(a) {};
85 # const repl = require('repl');
86 # var replServer = repl.start('');
87 #
88 # no prompt, or else readline complete seems to be confused, based
89 # on our column being different? node probably needs to send
90 # different kind of escape sequence that is not ugly. Anyways,
91 # completion doesnt work yet even with the ugly prompt, so whatever
92 #
93 export NODE_NO_READLINE=1
94
95 fi
96
97 # emacs has a different default search path than the info command. This
98 # adds the info defaults to emacs, but not the reverse, because I dun
99 # care much about the cli. The search path is only on the cli if you run
100 # "info xxx", or in emacs if you run '(info xxx)', so not that
101 # important, but might as well fix it.
102
103 # info info says this path is what was compiled, and its not documented
104 # anywhere. Through source grepping, i found it in filesys.h of the info
105 # source in trisquel flidas.
106 #
107 # Traling : means for emacs to add its own stuff on to the end.
108
109 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:.:
110
111 if [[ $- == *i* ]]; then
112 # for readline-complete.el
113 if [[ $RLC_INSIDE_EMACS ]]; then
114 # all for readline-complete.el
115 stty echo
116 bind 'set horizontal-scroll-mode on'
117 bind 'set print-completions-horizontally on'
118 bind '"\C-i": self-insert'
119 else
120
121 if [[ $KONSOLE_PROFILE_NAME ]]; then
122 TERM=xterm-256color
123 fi
124
125 # todo: not sure this works in sakura
126 #stty werase undef
127 #bind "\C-w": kill-region
128 # sakura == xterm-256color
129 # konsole == xterm
130 if [[ $TERM == xterm* ]]; then
131 # control + arrow keys. for other terminals, see http://unix.stackexchange.com/questions/10806/how-to-change-previous-next-word-shortcut-in-bash
132 bind '"\e[1;5C": shell-forward-word' 2>/dev/null
133 bind '"\e[1;5D": shell-backward-word' 2>/dev/null
134 else
135 # make ctrl-backspace work. for konsole, i fixed it through
136 # /home/iank/.local/share/konsole/default.keytab
137 stty werase '^h'
138 bind '"\eOc": shell-forward-word'
139 bind '"\eOd": shell-backward-word'
140 fi
141 # i cant remember why i did this, probably to free up some keys to bind
142 # to other things in bash.
143 # other than C-c and C-z, the rest defined by stty -a are, at least in
144 # gnome-terminal, overridden by bash, or disabled by the system
145 stty lnext undef stop undef start undef
146 fi
147
148 fi
149
150
151 # history number. History expansion is good.
152 PS4='$LINENO+ '
153 # history file size limit, set to unlimited.
154 # this needs to be different from the default because
155 # default HISTFILESIZE is 500 and could clobber our history
156 HISTFILESIZE=
157 # max commands 1 session can append/read from history
158 HISTSIZE=100000
159 # my own history size limit based on lines
160 HISTFILELINES=1000000
161 HISTFILE=$HOME/.bh
162 # the time format display when doing the history command
163 # also, setting this makes the history file record time
164 # of each command as seconds from the epoch
165 HISTTIMEFORMAT="%Y-%m-%d %I:%M %p "
166 # consecutive duplicate lines dont go in history
167 HISTCONTROL=ignoredups
168 # works in addition to HISTCONTROL to do more flexible things
169 # it could also do the same things as HISTCONTROL and thus replace it,
170 # but meh. dunno why, but just " *" does glob expansion, so use [ ] to avoid it.
171 HISTIGNORE='pass *:[ ]*:otp *:oathtool *'
172
173 export BC_LINE_LENGTH=0
174
175 export PROFILE_TASKS_TASK_OUTPUT_LIMIT=100
176
177 # note, if I use a machine I dont want files readable by all users, set
178 # umask 077 # If fewer than 4 digits are entered, leading zeros are assumed
179
180 # i for insensitive. the rest from
181 # X means dont remove the current screenworth of output upon exit
182 # R means to show colors n things
183 export LESS=RXi
184 export SYSTEMD_LESS=$LESS
185
186 # * include files
187
188 # generated instead of dynamic for the benefit of shellcheck
189 #for x in /a/bin/distro-functions/src/* /a/bin/!(githtml)/*-function?(s); do echo source $x ; done
190 source /a/bin/distro-functions/src/identify-distros
191 source /a/bin/distro-functions/src/package-manager-abstractions
192 source /a/bin/distro-setup/path_add-function
193 source /a/bin/ds/path_add-function
194 source /a/bin/log-quiet/logq-function
195 source /a/bin/small-misc-bash/ll-function
196 source /a/bin/small-misc-bash/psg-function
197 # for x in /a/bin/bash_unpublished/source-!(.#*); do echo source $x; done
198 source /a/bin/bash_unpublished/source-semi-priv
199 source /a/bin/bash_unpublished/source-state
200
201 # shellcheck source=./path_add-function
202 source $(dirname $(readlink -f $BASH_SOURCE))/path_add-function
203 source /a/bin/log-quiet/logq-function
204 # if someone exported $SOE (stop on error), catch errors.
205 #
206 # Note, on debian this results in the following warning when in ssh,
207 # hich I haven't figured out how to fix. It doesn't happen if we source
208 # after the shell has started
209 #
210 # bash: /usr/share/bashdb/bashdb-main.inc: No such file or directory
211 # bash: warning: cannot start debugger; debugging mode disabled
212 if [[ $SOE ]]; then
213 if [[ -e /a/bin/errhandle/err ]]; then
214 source /a/bin/errhandle/err
215 fi
216 fi
217
218 path_add /a/exe
219 # add this with absolute paths as needed for better security
220 #path_add --end /path/to/node_modules/.bin
221
222 # pip3 --user things go here:
223 path_add --end ~/.local/bin
224 path_add --ifexists --end /a/work/libremanage
225 path_add --ifexists --end /a/opt/adt-bundle*/tools /a/opt/adt-bundle*/platform-tools
226 path_add --ifexists --end /a/opt/scancode-toolkit-3.0.2
227 export WCDHOME=/a
228 # based on readme.debian. dunno if this will break on other distros.
229 if [[ -s /usr/share/wcd/wcd-include.sh ]]; then
230 source /usr/share/wcd/wcd-include.sh
231 fi
232
233
234 # * aliases
235
236 # very few aliases, functions are always preferred.
237
238 # ancient stuff.
239 if [[ $OS == Windows_NT ]]; then
240 alias ffs='cygstart "/c/Program Files (x86)/Mozilla Firefox/firefox.exe" -P scratch'
241 export DISPLAY=nt
242 alias j='command cygpath'
243 alias t='command cygstart'
244 alias cygstart='echo be quick, use the alias "t" instead :\)'
245 alias cygpath='echo be quick, use the alias "j" instead :\)'
246 fi
247
248
249
250 # keep this in mind? good for safety.
251 # alias cp='cp -i'
252 # alias mv='mv -i'
253
254
255 # remove any default aliases for these
256 unalias ls ll grep &>/dev/null ||:
257
258
259
260 # * functions
261
262
263 ..() { c ..; }
264 ...() { c ../..; }
265 ....() { c ../../..; }
266 .....() { c ../../../..; }
267 ......() { c ../../../../..; }
268
269
270 # file cut copy and paste, like the text buffers :)
271 # I havnt tested these.
272 _fbufferinit() { # internal use
273 ! [[ $my_f_tempdir ]] && my_f_tempdir=$(mktemp -d)
274 rm -rf "${my_f_tempdir:?}"/*
275 }
276 fcp() { # file cp
277 _fbufferinit
278 cp "$@" "$my_f_tempdir"/
279 }
280 fct() { # file cut
281 _fbufferinit
282 mv "$@" "$my_f_tempdir"/
283 }
284 fpst() { # file paste
285 [[ $2 ]] && { echo too many arguments; return 1; }
286 target=${1:-.}
287 cp "$my_f_tempdir"/* "$target"
288 }
289
290
291 # todo, update this
292 complete -F _longopt la lower low rlt rld rl lld ts ll dircp ex fcp fct fpst gr
293
294
295 _cdiff-prep() {
296 # join options which are continued to multiples lines onto one line
297 local first=true
298 while IFS= read -r line; do
299 # remove leading spaces/tabs. assumes extglob
300 if [[ $line == "[ ]*" ]]; then
301 line="${line##+( )}"
302 fi
303 if $first; then
304 pastline="$line"
305 first=false
306 elif [[ $line == *=* ]]; then
307 echo "$pastline" >> "$2"
308 pastline="$line"
309 else
310 pastline="$pastline $line"
311 fi
312 done < <(grep -vE '^([ \t]*#|^[ \t]*$)' "$1")
313 echo "$pastline" >> "$2"
314 }
315
316 _khfix_common() {
317 local host=${1##*@}
318 local ip port
319 read -r ip port < <(timeout 1 ssh -oBatchMode=yes -oControlMaster=no -oControlPath=/ -v $1 |& sed -rn "s/debug1: Connecting to $host \[([^\]*)] port ([0-9]+).*/\1 \2/p")
320 if [[ ! $ip ]]; then
321 echo "khfix: ssh failed"
322 return 1
323 fi
324 if [[ $port != 22 ]]; then
325 ip_entry="[$ip]:$port"
326 host_entry="[$host]:$port"
327 else
328 ip_entry=$ip
329 host_entry=$host
330 fi
331 ssh-keygen -R "$host_entry" -f $(readlink -f ~/.ssh/known_hosts)
332 echo "khfix: removing key for $ip_entry"
333 ssh-keygen -R "$ip_entry" -f $(readlink -f ~/.ssh/known_hosts)
334 }
335 khfix() { # known hosts fix
336 _khfix_common "$@" || return 1
337 ssh $1 :
338 }
339 khcopy() {
340 _khfix_common "$@"
341 ssh-copy-id $1
342 }
343
344 a() {
345 local x
346 x=$(readlink -nf "${1:-$PWD}")
347 # yes, its kinda dumb that xclip/xsel cant do this in one invocation
348 echo -n "$x" | xclip -selection clipboard
349 echo -n "$x" | xclip
350 }
351
352 ack() { ack-grep "$@"; }
353
354 anki() {
355 if which anki &>/dev/null; then
356 command anki
357 else
358 schroot -c anki -- anki
359 fi
360 }
361
362 ap() {
363 # pushd in case current directory has an ansible.cfg file
364 pushd /a/xans >/dev/null
365 ansible-playbook -v -l ${1:- $(hostname -f)} site.yml
366 popd >/dev/null
367 }
368 aw() {
369 pushd /a/work/ansible-configs >/dev/null
370 time ansible-playbook -v -i inventory adhoc.yml "$@"
371 popd >/dev/null
372 }
373 ad() {
374 pushd /a/bin/distro-setup/a >/dev/null
375 ansible-playbook site.yml
376 popd >/dev/null
377 }
378
379 astudio() {
380 # googling android emulator libGL error: failed to load driver: r600
381 # lead to http://stackoverflow.com/a/36625175/14456
382 export ANDROID_EMULATOR_USE_SYSTEM_LIBS=1
383 /a/opt/android-studio/bin/studio.sh "$@" &r;
384 }
385
386 b() {
387 # backwards
388 c -
389 }
390
391 bbk() {
392 c /
393 local active=true
394 systemctl is-active btrbk.timer || active=false
395 if $active; then
396 ser disable btrbk.timer
397 fi
398 if systemctl is-active btrbk.service; then
399 $active && ser enable btrbk.timer
400 echo "cron btrbk is already running"
401 return 1
402 fi
403 # run latest
404 install-my-scripts
405 btrbk-run "$@"
406 $active && ser enable btrbk.timer
407 }
408
409 bfg() { java -jar /a/opt/bfg-1.12.14.jar "$@"; }
410
411 bigclock() {
412 xclock -digital -update 1 -face 'arial black-80:bold'
413 }
414
415 bpull() {
416 [[ $1 ]] || return 1
417 c /
418 # run latest
419 install-my-scripts
420 switch-mail-host $1 $HOSTNAME
421 }
422 bpush() {
423 [[ $1 ]] || return 1
424 c /
425 # run latest
426 install-my-scripts
427 switch-mail-host $HOSTNAME $1
428 }
429
430
431 btc() {
432 local f=/etc/bitcoin/bitcoin.conf
433 # importprivkey will timeout if using the default of 15 mins.
434 # upped it to 1 hour.
435 bitcoin-cli -rpcclienttimeout=60000 -$(s grep rpcuser= $f) -$(s grep rpcpassword= $f) "$@"
436 }
437
438 btcusd() { # $1 btc in usd
439 local price
440 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
441 printf "$%s\n" "$price"
442 if [[ $1 ]]; then
443 printf "$%.2f\n" "$(echo "scale=4; $price * $1"| bc -l)"
444 fi
445 }
446 usdbtc() { # $1 usd in btc
447 local price
448 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
449 printf "$%s\n" "$price"
450 if [[ $1 ]]; then
451 # 100 mil satoshi / btc. 8 digits after the 1.
452 printf "%.8f btc\n" "$(echo "scale=10; $1 / $price "| bc -l)"
453 fi
454 }
455 satoshi() { # $1 satoshi in usd
456 local price
457 price="$(curl -s https://api.coinbase.com/v2/prices/BTC-USD/spot | jq -r .data.amount)"
458 price=$(echo "scale=10; $price * 0.00000001"| bc -l)
459 printf "$%f\n" "$price"
460 if [[ $1 ]]; then
461 printf "$%.2f\n" "$(echo "scale=10; $price * $1"| bc -l)"
462 fi
463 }
464
465
466 # c. better cd
467 if [[ $RLC_INSIDE_EMACS ]]; then
468 c() { wcd -c -z 50 -o "$@"; }
469 else
470 # lets see what the fancy terminal does from time to time
471 c() { wcd -c -z 50 "$@"; }
472 fi
473
474 caa() { git commit --amend --no-edit -a; }
475
476 caf() {
477 # shellcheck disable=SC2033
478 find -L $1 -type f -not \( -name .svn -prune -o -name .git -prune \
479 -o -name .hg -prune -o -name .editor-backups -prune \
480 -o -name .undo-tree-history -prune \) \
481 -exec bash -lc 'hr; echo "$1"; hr; cat "$1"' _ {} \; 2>/dev/null
482
483 }
484
485 calc() { echo "scale=3; $*" | bc -l; }
486 # no having to type quotes, but also no command history:
487 clc() {
488 local x
489 read -r x
490 echo "scale=3; $x" | bc -l
491 }
492
493 cam() {
494 git commit -am "$*"
495 }
496
497 cbfstool () { /a/opt/coreboot/build/cbfstool "$@"; }
498
499 ccat () { # config cat. see a config without extra lines.
500 grep '^\s*[^;[:space:]#]' "$@"
501 }
502
503 cdiff() {
504 # diff config files,
505 # setup for format of postfix, eg:
506 # option = stuff[,]
507 # [more stuff]
508 local pastline unified f1 f2
509 unified="$(mktemp)"
510 f1="$(mktemp)"
511 f2="$(mktemp)"
512 _cdiff-prep "$1" "$f1"
513 _cdiff-prep "$2" "$f2"
514 cat "$f1" "$f2" | grep -Po '^[^=]+=' | sort | uniq > "$unified"
515 while IFS= read -r line; do
516 # the default bright red / blue doesnt work in emacs shell
517 dwdiff -cblue,red -A best -d " ," <(grep "^$line" "$f1" || echo ) <(grep "^$line" "$f2" || echo ) | colordiff
518 done < "$unified"
519 }
520
521 cgpl()
522 {
523 if (($#)); then
524 cp /a/bin/data/COPYING "$@"
525 else
526 cp /a/bin/data/COPYING .
527 fi
528 }
529
530 capache()
531 {
532 if (($#)); then
533 cp /a/bin/data/LICENSE "$@"
534 else
535 cp /a/bin/data/LICENSE .
536 fi
537 }
538
539 cat-new-files() {
540 local start=$SECONDS
541 local dir="$1"
542 inotifywait -m "$dir" -e create -e moved_to |
543 # shellcheck disable=SC2030
544 while read -r filedir _ file; do
545 cat "$filedir$file"
546 hr
547 calc $((SECONDS - start)) / 60
548 sleep 5
549 done
550
551 }
552
553 # shellcheck disable=SC2032
554 chown() {
555 # makes it so chown -R symlink affects the symlink and its target.
556 if [[ $1 == -R ]]; then
557 shift
558 command chown -h "$@"
559 command chown -R "$@"
560 else
561 command chown "$@"
562 fi
563 }
564
565 cim() {
566 git commit -m "$*"
567 }
568
569 cl() {
570 # choose recent directory. cl = cd list
571 c =
572 }
573
574 chrome() {
575 if type -p chromium &>/dev/null; then
576 cmd=chromium
577 else
578 cd
579 cmd="schroot -c stretch chromium"
580 CHROMIUM_FLAGS='--enable-remote-extensions' $cmd &r
581 fi
582 }
583
584 d() { builtin bg; }
585 complete -A stopped -P '"%' -S '"' d
586
587 dat() { # do all tee, for more complex scripts
588 tee >(ssh frodo bash -l) >(bash -l) >(ssh x2 bash -l) >(ssh tp bash -l)
589 }
590 da() { # do all
591 local host
592 "$@"
593 for host in x2 tp kd; do
594 ssh $host $(printf "")
595 done
596 }
597
598 dc() {
599 diff --strip-trailing-cr -w "$@" # diff content
600 }
601
602 debian_pick_mirror () {
603 # netselect-apt finds a fast mirror.
604 # but we need to replace the mirrors ourselves,
605 # because it doesnt do that. best it can do is
606 # output a basic sources file
607 # here we get the server it found, get the main server we use
608 # then substitute all instances of one for the other in the sources file
609 # and backup original to /etc/apt/sources.list-original.
610 # this is idempotent. the only way to identify debian sources is to
611 # note the original server, so we put it in a comment so we can
612 # identify it later.
613 local file
614 file=$(mktemp -d)/f # safe way to get file name without creating one
615 sudo netselect-apt -o "$file" || return 1
616 url=$(grep ^\\w $file | head -n1 | awk '{print $2}')
617 sudo cp -f /etc/apt/sources.list /etc/apt/sources.list-original
618 sudo sed -ri "/http.us.debian.org/ s@( *[^ #]+ +)[^ ]+([^#]+).*@\1$url\2# http.us.debian.org@" /etc/apt/sources.list
619 sudo apt-get update
620 }
621
622 despace() {
623 local x y
624 for x in "$@"; do
625 y="${x// /_}"
626 safe_rename "$x" "$y"
627 done
628 }
629
630 dt() {
631 date "+%A, %B %d, %r" "$@"
632 }
633
634 dus() { # du, sorted, default arg of
635 du -sh ${@:-*} | sort -h
636 }
637
638
639
640 e() { echo "$@"; }
641
642 # echo var. print var including escapes, etc
643 ev() {
644 printf "%qEOL\n" "${!1}"
645 printf "%s" "${!1}" |& hexdump -C
646 }
647
648
649 ediff() {
650 [[ ${#@} == 2 ]] || { echo "error: ediff requires 2 arguments"; return 1; }
651 emacs --eval "(ediff-files \"$1\" \"$2\")"
652 }
653
654
655 envload() { # load environment from a previous: export > file
656 local file=${1:-$HOME/.${USER}_env}
657 eval "$(export | sed 's/^declare -x/export -n/')"
658 while IFS= read -r line; do
659 # declare -x makes variables local to a function
660 eval ${line/#declare -x/export}
661 done < "$file"
662 }
663
664 # mail related
665 etail() {
666 tail -F /var/log/exim4/mainlog -n 200
667 }
668 eless() {
669 less /var/log/exim4/mainlog
670 }
671
672 # shellcheck disable=SC2032
673 f() {
674 # cd forward
675 c +
676 }
677
678 fa() {
679 # find array. make an array of file names found by find into $x
680 # argument: find arguments
681 # return: find results in an array $x
682 while read -rd ''; do
683 x+=("$REPLY");
684 done < <(find "$@" -print0);
685 }
686
687 faf() { # find all files
688 find -L $1 -not \( -name .svn -prune -o -name .git -prune \
689 -o -name .hg -prune -o -name .editor-backups -prune \
690 -o -name .undo-tree-history -prune \) -type f 2>/dev/null
691 }
692
693 # one that comes with distros is too old for newer devices
694 fastboot() {
695 /a/opt/android-platform-tools/fastboot "$@";
696 }
697
698 kdecd() { /usr/lib/x86_64-linux-gnu/libexec/kdeconnectd; }
699
700 # List of apps to install/update
701 # Create from existing manually installed apps by doing
702 # fdroidcl update
703 # fdroidcl search -i, then manually removing
704 # automatically installed/preinstalled apps
705
706 #
707 # # my attempt at recovering from boot loop:
708 # # in that case, boot to recovery (volume up, home button, power, let go of power after samsun logo)
709 # # then
710 # mount /dev/block/mmcblk0p12 /data
711 # cd /data
712 # find -iname '*appname*'
713 # rm -rf FOUND_DIRS
714 # usually good enough to just rm -rf /data/app/APPNAME
715 #
716 # currently broken:
717 # # causes replicant to crash
718 # org.quantumbadger.redreader
719 # org.kde.kdeconnect_tp
720
721 # not broke, but wont work without gps
722 #com.zoffcc.applications.zanavi
723 # not broke, but not using atm
724 #com.nutomic.syncthingandroid
725 # # doesn\'t work on replicant
726 #net.sourceforge.opencamera
727 #
728 fdroid_pkgs=(
729 de.marmaro.krt.ffupdater
730 me.ccrama.redditslide
731 org.fedorahosted.freeotp
732 at.bitfire.davdroid
733 com.alaskalinuxuser.justnotes
734 com.artifex.mupdf.viewer.app
735 com.danielkim.soundrecorder
736 com.fsck.k9
737 com.ghostsq.commander
738 com.ichi2.anki
739 com.jmstudios.redmoon
740 com.jmstudios.chibe
741 org.kde.kdeconnect_tp
742 com.notecryptpro
743 com.termux
744 cz.martykan.forecastie
745 de.danoeh.antennapod
746 de.blinkt.openvpn
747 de.marmaro.krt.ffupdater
748 eu.siacs.conversations
749 free.rm.skytube.oss
750 im.vector.alpha # riot
751 info.papdt.blackblub
752 me.tripsit.tripmobile
753 net.gaast.giggity
754 net.minetest.minetest
755 net.osmand.plus
756 org.isoron.uhabits
757 org.linphone
758 org.gnu.icecat
759 org.smssecure.smssecure
760 org.yaaic
761 sh.ftp.rocketninelabs.meditationassistant.opensource
762 )
763 # https://forum.xda-developers.com/android/software-hacking/wip-selinux-capable-superuser-t3216394
764 # for maru,
765 #me.phh.superuser
766
767 fdup() {
768 local -A installed updated
769 local p
770 fdroidcl update
771 if fdroidcl search -u | grep ^org.fdroid.fdroid; then
772 fdroidcl install org.fdroid.fdroid
773 sleep 5
774 fdroidcl update
775 fi
776 for p in $(fdroidcl search -i| grep -o "^\S\+"); do
777 installed[$p]=true
778 done
779 for p in $(fdroidcl search -u| grep -o "^\S\+"); do
780 updated[$p]=false
781 done
782 for p in ${fdroid_pkgs[@]}; do
783 if ! ${installed[$p]:-false}; then
784 fdroidcl install $p
785 # sleeps are just me being paranoid since replicant has a history of crashing when certain apps are installed
786 sleep 5
787 fi
788 done
789 for p in ${!installed[@]}; do
790 if ! ${updated[$p]:-true}; then
791 fdroidcl install $p
792 sleep 5
793 fi
794 done
795 }
796
797 firefox-default-profile() {
798 key=Default value=1 section=$1
799 file=/p/c/subdir_files/.mozilla/firefox/profiles.ini
800 sed -ri "/^ *$key/d" "$file"
801 sed -ri "/ *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d};/ *\[$section\]/a $key=$value" "$file"
802 }
803 fdhome() { #firefox default home profile
804 firefox-default-profile Profile0
805 }
806
807 fdwork() {
808 firefox-default-profile Profile4
809 }
810
811 ff() {
812 if type -P firefox &>/dev/null; then
813 firefox "$@"
814 else
815 iceweasel "$@"
816 fi
817 }
818
819
820
821 fn() {
822 firefox -P alt "$@" >/dev/null 2>&1
823 }
824
825
826 fsdiff () {
827 local missing=false
828 local dname="${PWD##*/}"
829 local m="/a/tmp/$dname-missing"
830 local d="/a/tmp/$dname-diff"
831 [[ -e $d ]] && rm "$d"
832 [[ -e $m ]] && rm "$m"
833 local msize=0
834 local fsfile
835 while read -r line; do
836 fsfile="$1${line#.}"
837 if [[ -e "$fsfile" ]]; then
838 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
839 else
840 missing=true
841 echo "$line" >> "$m"
842 msize=$((msize + 1))
843 fi
844 done < <(find . -type f )
845 if $missing; then
846 echo "$m"
847 (( msize <= 100 )) && cat $m
848 fi
849 }
850 fsdiff-test() {
851 # expected output, with different tmp dirs
852 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
853 # /a/tmp/tmp.qLDkYxBYPM-missing
854 # ./b
855 cd $(mktemp -d)
856 echo ok > a
857 echo nok > b
858 mkdir c
859 echo ok > c/d
860 local x
861 x=$(mktemp -d)
862 mkdir $x/c
863 echo different > $x/c/d
864 echo ok > $x/a
865 fsdiff $x
866 }
867 rename-test() {
868 # test whether missing files were renamed, generally for use with fsdiff
869 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
870 # echos non-renamed files
871 local x y found
872 unset sums
873 for x in "$2"/*; do
874 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
875 done
876 while read -r line; do
877 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
878 renamed=false
879 for x in "${sums[@]}"; do
880 if [[ $missing_sum == "$x" ]]; then
881 renamed=true
882 break
883 fi
884 done
885 $renamed || echo "$line"
886 done < "$1"
887 return 0
888 }
889
890 feh() {
891 # F = fullscren, z = random, Z = auto zoom
892 command feh -FzZ "$@"
893 }
894
895 # mail related
896 frozen() {
897 rm -rf /tmp/frozen
898 s mailq |gr frozen|awk '{print $3}' | while read -r id; do
899 s exim -Mvl $id
900 echo
901 s exim -Mvh $id
902 echo
903 s exim -Mvb $id
904 echo -e '\n\n##############################\n'
905 done | tee -a /tmp/frozen
906 }
907 frozenrm() {
908 local ids=()
909 while read -r line; do
910 printf '%s\n' "$line"
911 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
912 done < <(s mailq)
913 echo "sleeping for 2 in case you change your mind"
914 sleep 2
915 s exim -Mrm "${ids[@]}"
916 }
917
918 funce() {
919 # like -e for functions. returns on error.
920 # at the end of the function, disable with:
921 # trap ERR
922 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
923 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
924 trap ERR
925 return' ERR
926 }
927
928
929 fw() {
930 firefox -P default "$@" >/dev/null 2>&1
931 }
932
933 getdir () {
934 local help="Usage: getdir [--help] PATH
935 Output the directory of PATH, or just PATH if it is a directory."
936 if [[ $1 == --help ]]; then
937 echo "$help"
938 return 0
939 fi
940 if [[ $# -ne 1 ]]; then
941 echo "getdir error: expected 1 argument, got $#"
942 return 1
943 fi
944 if [[ -d $1 ]]; then
945 echo "$1"
946 else
947 local dir
948 dir="$(dirname "$1")"
949 if [[ -d $dir ]]; then
950 echo "$dir"
951 else
952 echo "getdir error: directory does not exist"
953 return 1
954 fi
955 fi
956 }
957
958 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
959 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
960 local root
961 root=$(gitroot) || return 1 # function to set gitroot
962 builtin cd "$root"
963 git symbolic-ref HEAD refs/heads/$1
964 rm .git/index
965 git clean -fdx
966 }
967
968 # shellcheck disable=SC2120
969 gitroot() {
970 local help="Usage: gitroot [--help]
971 Print the full path to the root of the current git repo
972
973 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
974 and works in older versions of git which did not have that."
975 if [[ $1 == --help ]]; then
976 echo "$help"
977 return
978 fi
979 local p
980 p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
981 [[ $p != /* ]] && p=$PWD
982 echo "${p%%/.git}"
983 }
984
985 gitian() {
986 git config user.email ian@iankelling.org
987 }
988
989 gh() {
990 # i got an error, gh not found when doing a pull request, it seems like it wants itself in it\'s path.
991 local _oldpath="$PATH"
992 PATH="$PATH:$HOME/node_modules/.bin"
993 command gh "$@"
994 PATH="$_oldpath"
995 }
996
997 gmacs() {
998 # quit will prompt if the program crashes.
999 gdb -ex=r -ex=quit --args emacs "$@"; r;
1000 }
1001
1002 gdkill() {
1003 # kill the emacs daemon
1004 pk1 emacs --daemon
1005 }
1006
1007 # at least in flidas, things rely on gpg being gpg1
1008 gpg() {
1009 command gpg2 "$@"
1010 }
1011
1012 gse() {
1013 local email=ian@iankelling.org
1014 if readlink ~/.mu | grep fsf &>/dev/null; then
1015 email=iank@fsf.org
1016 fi
1017 git send-email --notes "--envelope-sender=<$email>" \
1018 --suppress-cc=self "$@"
1019 }
1020
1021 gr() {
1022 grep -iIP --color=auto "$@"
1023 }
1024
1025 grr() { # grep recursive
1026 if [[ ${#@} == 1 ]]; then
1027 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@" .
1028 else
1029 grep --exclude-dir='*.emacs.d' --exclude-dir='*.git' -RiIP --color=auto "$@"
1030 fi
1031 }
1032 rg() {
1033 command rg -i -M 200 "$@"
1034 }
1035
1036 hstatus() {
1037 # do git status on published repos
1038 cd /a/bin/githtml
1039 for x in *; do
1040 cd $(readlink -f $x)/..
1041 status=$(i status -s) || pwd
1042 if [[ $status ]]; then
1043 hr
1044 echo $x
1045 printf "%s\n" "$status"
1046 fi
1047 cd /a/bin/githtml
1048 done
1049 }
1050
1051 hl() { # history limit. Write extra history to archive file.
1052 # todo: this is not working or not used currently
1053 local max_lines linecount prune_lines x
1054 local harchive="${HISTFILE}_archive"
1055 for x in "$HISTFILE" "$harchive"; do
1056 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
1057 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != "$EUID" ]]; then
1058 echo "error in hl: history file \$x:$x no good"
1059 return 1
1060 fi
1061 done
1062 history -a # save history
1063 max_lines=$HISTFILELINES
1064 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
1065 linecount=$(wc -l < $HISTFILE) # pipe so it doesnt output a filename
1066 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
1067 if ((linecount > max_lines)); then
1068 prune_lines=$((linecount - max_lines))
1069 head -n $prune_lines "$HISTFILE" >> "$harchive" \
1070 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
1071 fi
1072 }
1073
1074 hr() { # horizontal row. used to break up output
1075 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq ${COLUMNS:-60})
1076 echo
1077 }
1078
1079 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
1080
1081 # get latest hub and run it
1082 # main command to use:
1083 # hub pull-request --no-edit
1084 # --no-edit means to use the first commit\'s message as the pull request message.
1085 # Also, you need to use a feature branch, not master in your fork.
1086 # On first use, you input username/pass and it gets an oath token so you dont have to repeat
1087 # it\'s at ~/.config/hub
1088 hub() {
1089 local up uptar updir p
1090 p=/github/hub/releases/
1091 up=https://github.com/$(curl -s https://github.com$p| grep -o $p'download/[^/]*/hub-linux-amd64[^"]*' | head -n1)
1092 uptar=${up##*/}
1093 updir=${uptar%.tgz}
1094 if [[ ! -e /a/opt/$updir ]]; then
1095 rm -rf /a/opt/hub-linux-amd64*
1096 wget -P /a/opt $up
1097 tar -C /a/opt -zxf /a/opt/$uptar
1098 rm -f /a/opt/$uptar
1099 s /a/opt/$updir/install
1100 fi
1101
1102 # save token across computers
1103 if [[ ! -L ~/.config/hub ]]; then
1104 if [[ -e ~/.config/hub ]]; then
1105 mv ~/.config/hub /p/c/subdir_files/.config/
1106 fi
1107 if [[ -e /p/c/subdir_files/.config/hub ]]; then
1108 conflink
1109 fi
1110 fi
1111 command hub "$@"
1112 }
1113
1114 i() { git "$@"; }
1115 # modified from ~/local/bin/git-completion.bash
1116 # other completion commands are mostly taken from bash_completion package
1117 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
1118 || complete -o default -o nospace -F _git i
1119
1120 if ! type service &>/dev/null; then
1121 service() {
1122 echo actually running: systemctl $2 $1
1123 systemctl $2 $1
1124 }
1125 fi
1126
1127 ic() {
1128 # fast commit all
1129 git commit -am "$*"
1130 }
1131
1132
1133 idea() {
1134 /a/opt/idea-IC-163.7743.44/bin/idea.sh "$@" &r
1135 }
1136
1137 ifn() {
1138 # insensitive find
1139 find -L . -not \( -name .svn -prune -o -name .git -prune \
1140 -o -name .hg -prune -o -name .editor-backups -prune \
1141 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
1142 }
1143
1144
1145 o() {
1146 if type gvfs-open &> /dev/null ; then
1147 gvfs-open "$@"
1148 else
1149 xdg-open "$@"
1150 fi
1151 # another alternative is run-mailcap
1152 }
1153
1154 ipdrop() {
1155 s iptables -A INPUT -s $1 -j DROP
1156 }
1157
1158
1159 istext() {
1160 grep -Il "" "$@" &>/dev/null
1161 }
1162
1163 jfilter() {
1164 grep -Evi -e "^(\S+\s+){4}(sudo|sshd|cron)\[\S*:" \
1165 -e "^(\S+\s+){4}systemd\[\S*: (starting|started) (btrfsmaintstop|dynamicipupdate|spamd dns bug fix cronjob|rss2email)\.*$"
1166 }
1167 jtail() {
1168 journalctl -n 10000 -f "$@" | jfilter
1169 }
1170 jr() { journalctl "$@" | jfilter | less ; }
1171 jrf() { journalctl -f "$@" | jfilter; }
1172
1173 kff() { # keyboardio firmware flash
1174 pushd /a/bin/distro-setup/Arduino/Model01-Firmware
1175 yes $'\n' | make flash
1176 popd
1177 }
1178
1179 l() {
1180 if [[ $PWD == /[iap] ]]; then
1181 command ls -A --color=auto -I lost+found "$@"
1182 else
1183 command ls -A --color=auto "$@"
1184 fi
1185 }
1186
1187
1188 lcn() { locate -i "*$**"; }
1189
1190 lg() { LC_COLLATE=C.UTF-8 ll --group-directories-first; }
1191
1192 lt() { ll -tr "$@"; }
1193
1194 lld() { ll -d "$@"; }
1195
1196 lom() {
1197 local l base
1198 if [[ $1 == /* ]]; then
1199 base=${1##*/}
1200 if mountpoint /mnt/$base; then
1201 return 0
1202 fi
1203 l=$(sudo losetup -f)
1204 sudo losetup $l $1
1205 if ! sudo cryptsetup luksOpen $l $base; then
1206 sudo losetup -d $l
1207 return 1
1208 fi
1209 sudo mkdir -p /mnt/$base
1210 sudo mount /dev/mapper/$base /mnt/$base
1211 sudo chown $USER:$USER /mnt/$base
1212 else
1213 base=$1
1214 sudo umount /mnt/$base
1215 l=$(sudo cryptsetup status /dev/mapper/$base|sed -rn 's/^\s*device:\s*(.*)/\1/p')
1216 sudo cryptsetup luksClose /dev/mapper/$base || return 1
1217 sudo losetup -d $l
1218 fi
1219 }
1220
1221 low() { # make filenames lowercase, remove bad chars
1222 local f new
1223 for f in "$@"; do
1224 new="${f,,}" # downcase
1225 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
1226 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1227 new="${new%"${new##*[[:alnum:]]}"}"
1228 # remove bad underscores, like __ and _._
1229 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1230 safe_rename "$f" "$new" || return 1
1231 done
1232 return 0
1233 }
1234
1235 lower() { # make first letter of filenames lowercase.
1236 local x
1237 for x in "$@"; do
1238 if [[ ${x::1} == [A-Z] ]]; then
1239 y=$(tr '[:upper:]' '[:lower:]' <<<"${x::1}")"${x:1}"
1240 safe_rename "$x" "$y" || return 1
1241 fi
1242 done
1243 }
1244
1245
1246 k() { # history search
1247 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80;
1248 }
1249
1250 ks() { # history search
1251 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq;
1252 }
1253
1254
1255 make-targets() {
1256 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1257 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1258 }
1259
1260 mbenable() {
1261 local mb=$1
1262 dst=/m/4e/$mb
1263 src=/m/md/$mb
1264 set -x
1265 [[ -e $src ]] || { set +x; return 1; }
1266 mv -T $src $dst || { set +x; return 1; }
1267 ln -s -T $dst $src
1268 /a/exe/lnf /p/.mu ~
1269 mu index --maildir=/m/4e
1270 set +x
1271 }
1272 mbdisable() {
1273 local mb=$1
1274 dst=/m/md/$mb
1275 src=/m/4e/$mb
1276 set -x
1277 [[ -e $src ]] || { set +x; return 1; }
1278 if [[ -L $dst ]]; then rm $dst; fi
1279 mv -T $src $dst
1280 set +x
1281 }
1282
1283
1284 mdt() {
1285 markdown "$1" >/tmp/mdtest.html
1286 firefox /tmp/mdtest.html
1287 }
1288
1289
1290 mkc() {
1291 mkdir "$1"
1292 c "$1"
1293 }
1294
1295 mkct() {
1296 mkc $(mktemp -d)
1297 }
1298
1299 mkt() { # mkdir and touch file
1300 local path="$1"
1301 mkdir -p "$(dirname "$path")"
1302 touch "$path"
1303 }
1304
1305 # shellcheck disable=SC2032
1306 mkdir() { command mkdir -p "$@"; }
1307
1308 mo() { xset dpms force off; } # monitor off
1309
1310 net-dev-info() {
1311 e "lspci -nnk|gr -iA2 net"
1312 lspci -nnk|gr -iA2 net
1313 hr
1314 e "s lshw -C network"
1315 hr
1316 s lshw -C network
1317
1318 }
1319
1320 nk() {
1321 ser stop NetworkManager
1322 ser stop dnsmasq
1323 s resolvconf -d NetworkManager
1324 ser start dnsmasq
1325 s ifup br0
1326 }
1327 ngo() {
1328 s ifdown br0
1329 ser start NetworkManager
1330 sleep 4
1331 s nmtui-connect
1332 }
1333
1334 nopanic() {
1335 # shellcheck disable=SC2024
1336 sudo tee -a /var/log/exim4/paniclog-archive </var/log/exim4/paniclog; sudo truncate -s0 /var/log/exim4/paniclog
1337 }
1338
1339
1340 otp() {
1341 oathtool --totp -b "$@" | xclip -selection clipboard
1342 }
1343
1344 p8() { ping 8.8.8.8; }
1345
1346 pakaraoke() {
1347 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
1348 pactl load-module module-ladspa-sink sink_name=Karaoke master=alsa_output.usb-Audioengine_Audioengine_D1-00.analog-stereo plugin=karaoke_1409 label=karaoke control=-30
1349 }
1350
1351
1352 pfind() { #find *$1* in $PATH
1353 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
1354 local pathArray
1355 IFS=: pathArray=($PATH); unset IFS
1356 find "${pathArray[@]}" -iname "*$1*"
1357 }
1358
1359 pkx() { # package extract
1360 local pkg cached tmp f
1361 c $(mktemp -d)
1362 pkg=$1
1363 # shellcheck disable=SC2012
1364 cached=$(ls -t /var/cache/apt/archives/$pkg* | tail -n1)
1365 if [[ $cached ]]; then
1366 cp $cached .
1367 else
1368 aptitude download $pkg
1369 fi
1370 tmp=(*); f=${tmp[0]} # only 1 expected
1371 ex $f
1372 rm -f $f
1373 }
1374
1375 pk1() {
1376 local pid
1377 pid=($(pgrep -f "$*"))
1378 case ${#pid[@]} in
1379 1)
1380 # shellcheck disable=SC2128
1381 {
1382 ps -F $pid
1383 m kill $pid
1384 }
1385 ;;
1386 0) echo "no pid found" ;;
1387 *)
1388 ps -F ${pid[@]}
1389 ;;
1390 esac
1391 }
1392
1393 pick-trash() {
1394 # trash-restore lists everything that has been trashed at or below CWD
1395 # This picks out files just in CWD, not subdirectories,
1396 # which also match grep $1, usually use $1 for a time string
1397 # which you get from running restore-trash once first
1398 local name x ask
1399 local nth=1
1400 # last condition is to not ask again for ones we skipped
1401 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
1402 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
1403 name="$(echo "$name" | head -n $nth | tail -n 1 )"
1404 read -r -p "$name [Y/n] " ask
1405 if [[ ! $ask || $ask == [Yy] ]]; then
1406 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
1407 echo $x | restore-trash > /dev/null
1408 elif [[ $ask == [Nn] ]]; then
1409 nth=$((nth+1))
1410 else
1411 return
1412 fi
1413 done
1414 }
1415
1416
1417 pub() {
1418 rld /a/h/_site/ li:/var/www/iankelling.org/html
1419 }
1420
1421 pubip() { curl -4s https://icanhazip.com; }
1422 pubip6() { curl -6s https://icanhazip.com; }
1423 whatismyip() { pubip; }
1424
1425 pumpa() {
1426 # fixes the menu bar in xmonad. this won\'t be needed when xmonad
1427 # packages catches up on some changes in future (this is written in
1428 # 4/2017)
1429 #
1430 # geekosaur: so youll want to upgrade to xmonad 0.13 or else use a
1431 # locally modified XMonad.Hooks.ManageDocks that doesnt set the
1432 # work area; turns out it\'s impossible to set correctly if you are
1433 # not a fully EWMH compliant desktop environment
1434 #
1435 # geekosaur: chrome shows one failure mode, qt/kde another, other
1436 # gtk apps a third, ... I came up with a setting that works for me
1437 # locally but apparently doesnt work for others, so we joined the
1438 # other tiling window managers in giving up on setting it at all
1439 #
1440 xprop -root -remove _NET_WORKAREA
1441 command pumpa &r
1442 }
1443
1444
1445 pwgen() {
1446 # -m = min length
1447 # -x = max length
1448 # -t = print pronunciation
1449 apg -m 14 -x 17 -t
1450 for (( i=0; i<10; i++ )); do
1451 shuf -n3 /usr/share/hunspell/en_US.dic | sed 's,/.*,,' | paste -sd . -
1452
1453 done
1454 }
1455
1456 pwlong() {
1457 # -M CLN = use Caps, Lowercase, Numbers
1458 # -n 1 = 1 password
1459 # -a 1 = use random instead of pronounceable algorithm
1460 apg -m 50 -x 70 -n 1 -a 1 -M CLN
1461 }
1462
1463
1464 q() { # start / launch a program in the backround and redir output to null
1465 "$@" &> /dev/null &
1466 }
1467
1468 # shellcheck disable=SC2120
1469 r() {
1470 history -a # save history
1471 exit ${1:0}
1472 # i had this redir, not sure why
1473 # exit "$@" 2>/dev/null
1474 }
1475
1476 rbpipe() { rbt post -o --diff-filename=- "$@"; }
1477 rbp() { rbt post -o "$@"; }
1478
1479 rebr() {
1480 s ifdown br0
1481 s ifup br0
1482 }
1483
1484 resolvcat() {
1485 local f
1486 f=/etc/resolv.conf
1487 echo $f:; ccat $f
1488 hr; echo dnsmasq is $(systemctl is-active dnsmasq)
1489 f=/var/run/dnsmasq/resolv.conf
1490 hr; echo $f:; ccat $f
1491 f=/etc/dnsmasq-servers.conf
1492 hr; echo $f:; ccat $f
1493 }
1494
1495 rl() {
1496 # rsync, root is required to keep permissions right.
1497 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1498 # --no-times --delete
1499 # basically, make an exact copy, use checksums instead of file times to be more accurate
1500 rsync -ahvic --delete "$@"
1501 }
1502 rld() {
1503 # like rlu, but dont delete files on the target end which
1504 # do not exist on the original end.
1505 rsync -ahvic "$@"
1506 }
1507 complete -F _rsync -o nospace rld rl rlt
1508
1509 rlt() {
1510 # rl without preserving modification time.
1511 rsync -ahvic --delete --no-t "$@"
1512 }
1513
1514 rlu() { # [OPTS] HOST PATH
1515 # eg. rlu -opts frodo /testpath
1516 # relative paths will expanded with readlink -f.
1517 opts=("${@:1:$#-2}") # 1 to last -2
1518 path="${*:$#}" # last
1519 host="${*:$#-1:1}" # last -1
1520 if [[ $path == .* ]]; then
1521 path=$(readlink -f $path)
1522 fi
1523 # rync here uses checksum instead of time so we dont mess with
1524 # unison relying on time as much. g is for group, same reason
1525 # to keep up with unison.
1526 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1527 }
1528
1529 # only run on MAIL_HOST. simpler to keep this on one system.
1530 r2eadd() { # usage: name url
1531 # initial setup of rss2email:
1532 # r2e new r2e@iankelling.org
1533 # that initializes files, and sets default email.
1534 # symlink to the config doesnt work, so I copied it to /p/c
1535 # and then use cli option to specify explicit path.
1536 # Only option changed from default config is to set
1537 # force-from = True
1538 #
1539 # or else for a few feeds, the from address is set by the feed, and
1540 # if I fail delivery, then I send a bounce message to that from
1541 # address, which makes me be a spammer.
1542
1543 r2e add $1 "$2" $1@r2e.iankelling.org
1544 # get up to date and dont send old entries now:
1545 r2e run --no-send $1
1546 }
1547 r2e() { command r2e -d /p/c/rss2email.json -c /p/c/rss2email.cfg "$@"; }
1548
1549 rspicy() { # usage: HOST DOMAIN
1550 # connect to spice vm remote host. use vspicy for local host
1551 local port
1552 # shellcheck disable=SC2087
1553 port=$(ssh $1<<EOF
1554 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
1555 sed -rn "s/.*port='([0-9]+).*/\1/p"
1556 EOF
1557 )
1558 if [[ $port ]]; then
1559 spicy -h $1 -p $port
1560 else
1561 echo "error: no port found. check that the domain is running."
1562 fi
1563 }
1564
1565 rmstrips() {
1566 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt | less
1567 }
1568
1569 s() {
1570 # background
1571 # I use a function because otherwise we cant use in a script,
1572 # cant assign to variable.
1573 #
1574 # note: gksudo is recommended for X apps because it does not set the
1575 # home directory to the same, and thus apps writing to ~ fuck things up
1576 # with root owned files.
1577 #
1578 if [[ $EUID != 0 || $1 == -* ]]; then
1579 SUDOD="$PWD" sudo -i "$@"
1580 else
1581 "$@"
1582 fi
1583 }
1584
1585 safe_rename() { # warn and dont rename if file exists.
1586 # mv -n exists, but it\'s silent
1587 if [[ $# != 2 ]]; then
1588 echo safe_rename error: $# args, need 2 >2
1589 return 1
1590 fi
1591 if [[ $1 != "$2" ]]; then # yes, we want to silently ignore this
1592 if [[ -e $2 || -L $2 ]]; then
1593 echo "Cannot rename $1 to $2 as it already exists."
1594 else
1595 mv -vi "$1" "$2"
1596 fi
1597 fi
1598 }
1599
1600
1601 sb() { # sudo bash -c
1602 # use sb instead of s is for sudo redirections,
1603 # eg. sb 'echo "ok fine" > /etc/file'
1604 local SUDOD="$PWD"
1605 sudo -i bash -c "$@"
1606 }
1607 complete -F _root_command s sb
1608
1609 scssl() {
1610 # s gem install scss-lint
1611 pushd /a/opt/thoughtbot-guides
1612 git pull --stat
1613 popd
1614 scss-lint -c /a/opt/thoughtbot-guides/style/sass/.scss-lint.yml "$@"
1615 }
1616
1617 ser() {
1618 local s; [[ $EUID != 0 ]] && s=s
1619 if type -p systemctl &>/dev/null; then
1620 $s systemctl $1 $2
1621 else
1622 $s service $2 $1
1623 fi
1624 }
1625 # like restart, but do nothing if its not already started
1626 srestart() {
1627 local service=$1
1628 if [[ $(s systemctl --no-pager show -p ActiveState $service ) == ActiveState=active ]]; then
1629 systemctl restart $service
1630 fi
1631 }
1632
1633 setini() { # set a value in a .ini style file
1634 key="$1" value="$2" section="$3" file="$4"
1635 if [[ -s $file ]]; then
1636 sed -ri -f - "$file" <<EOF
1637 # remove existing keys
1638 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1639 # add key
1640 /^\s*\[$section\]/a $key=$value
1641 # from section to eof, do nothing
1642 /^\s*\[$section\]/,\$b
1643 # on the last line, if we haven't found section yet, add section and key
1644 \$a [$section]\\
1645 $key=$value
1646 EOF
1647 else
1648 cat >"$file" <<EOF
1649 [$section]
1650 $key=$value
1651 EOF
1652 fi
1653 }
1654
1655 sgo() { # service go
1656 service=$1
1657 ser restart $service || return 1
1658 if type -p systemctl &>/dev/null; then
1659 ser enable $service
1660 fi
1661 }
1662
1663 sgu() {
1664 systemctl list-unit-files | rg "$@"
1665 }
1666
1667 sk() {
1668 # 2086: unquoted $var
1669 # 2046: unquoted $(cmd)
1670 # 2068: Double quote array expansions to avoid re-splitting elements.
1671 # 2119: Functions with optional args get bad warnings when none are passed.
1672 # 2033: too many false positives for thing that will never work, passing shell function to find.
1673 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1674 shellcheck -x -e 2086,2046,2068,2119,2033 "$@"
1675 # had this before. not sure what it is 2119
1676 }
1677
1678 skaraoke() {
1679 local tmp out
1680 out=${2:-${1%.*}.sh}
1681 tmp=$(mktemp -d)
1682 script -t -c "mpv --no-config --no-resume-playback --no-terminal --no-audio-display '$1'" $tmp/typescript 2>$tmp/timing
1683 # todo, the current sleep seems pretty good, but it
1684 # would be nice to have an empirical measurement, or
1685 # some better wait to sync up.
1686 #
1687 # note: --loop-file=no prevents it from hanging if you have that
1688 # set to inf the mpv config.
1689 # --loop=no prevents it from exit code 3 due to stdin if you
1690 # had it set to inf in mpv config.
1691 #
1692 # args go to mpv, for example --volume=80, 50%
1693 cat >$out <<EOFOUTER
1694 #!/bin/bash
1695 trap "trap - TERM && kill 0" INT TERM ERR; set -e
1696 ( sleep .2; scriptreplay <( cat <<'EOF'
1697 $(cat $tmp/timing)
1698 EOF
1699 ) <( cat <<'EOF'
1700 $(cat $tmp/typescript)
1701 EOF
1702 ))&
1703 base64 -d - <<'EOF'| mpv --loop=no --loop-file=no --no-terminal --no-audio-display "\$@" -
1704 $(base64 "$1")
1705 EOF
1706 kill 0
1707 EOFOUTER
1708 rm -r $tmp
1709 chmod +x $out
1710 }
1711
1712 slog() {
1713 # log with script. timing is $1.t and script is $1.s
1714 # -l to save to ~/typescripts/
1715 # -t to add a timestamp to the filenames
1716 local logdir do_stamp arg_base
1717 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1718 logdir="/a/dt/"
1719 do_stamp=false
1720 while getopts "lt" option
1721 do
1722 case $option in
1723 l ) arg_base=$logdir ;;
1724 t ) do_stamp=true ;;
1725 esac
1726 done
1727 shift $((OPTIND - 1))
1728 arg_base+=$1
1729 [[ -e $logdir ]] || mkdir -p $logdir
1730 $do_stamp && arg_base+=$(date +%F.%T%z)
1731 script -t $arg_base.s 2> $arg_base.t
1732 }
1733 splay() { # script replay
1734 #logRoot="$HOME/typescripts/"
1735 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1736 scriptreplay "$1.t" "$1.s"
1737 }
1738
1739 smeld() { # ssh meld usage host1 host2 file
1740 meld <(ssh $1 cat $3) <(ssh $2 cat $3)
1741 }
1742
1743 spd() {
1744 PATH=/usr/local/spdhackfix:$PATH command spd "$@"
1745 }
1746
1747 spend() {
1748 s systemctl suspend
1749 }
1750
1751 sr() {
1752 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1753 if [[ $# == 0 ]]; then
1754 sudo -E bash -c -l "$(history -p '!!')"
1755 else
1756 echo this command redos last history item. no argument is accepted
1757 fi
1758 }
1759
1760 srm () {
1761 # with -ll, less secure but faster.
1762 command srm -ll "$@"
1763 }
1764
1765 srun() {
1766 scp $2 $1:/tmp
1767 ssh $1 /tmp/${2##*/} $(printf "%q\n" "${@:2}")
1768 }
1769
1770 ssh() {
1771 BASH_LOGIN_SHELL=true command ssh "$@"
1772 }
1773 sss() { # ssh solo
1774 ssh -oControlMaster=no -oControlPath=/ "$@"
1775 }
1776 ssk() {
1777 local -a opts=()
1778 while [[ $1 == -* ]]; do
1779 opts+=("$1")
1780 shift
1781 done
1782 m pkill -f "^ssh: /tmp/ssh_mux_${USER}_${1#*@}_22_"
1783 m ssh "${opts[@]}" "$@"
1784 }
1785
1786 swap() {
1787 local tmp
1788 tmp=$(mktemp)
1789 mv $1 $tmp
1790 mv $2 $1
1791 mv $tmp $2
1792 }
1793
1794 t() {
1795 local x
1796 local -a args
1797 if type -t trash-put >/dev/null; then
1798 # skip args that dont exist, or else trash-put will have an error
1799 for x in "$@"; do
1800 if [[ -e $x || -L $x ]]; then
1801 args+=("$x")
1802 fi
1803 done
1804 (( ! ${#args[@]} )) || trash-put "${args[@]}"
1805 else
1806 rm -rf "$@"
1807 fi
1808 }
1809
1810
1811 tclock() {
1812 local x
1813 clear
1814 date +%l:%_M
1815 len=60
1816 # this goes to full width
1817 #len=${1:-$((COLUMNS -7))}
1818 x=1
1819 while true; do
1820 if (( x == len )); then
1821 end=true
1822 d="$(date +%l:%_M) "
1823 else
1824 end=false
1825 d=$(date +%l:%M:%_S)
1826 fi
1827 echo -en "\r"
1828 echo -n "$d"
1829 for ((i=0; i<x; i++)); do
1830 if (( i % 6 )); then
1831 echo -n _
1832 else
1833 echo -n .
1834 fi
1835 done
1836 if $end; then
1837 echo
1838 x=1
1839 else
1840 x=$((x+1))
1841 fi
1842 sleep 5
1843 done
1844 }
1845
1846
1847 te() {
1848 # test existence / exists
1849 local ret=0
1850 for x in "$@"; do
1851 [[ -e "$x" || -L "$x" ]] || ret=1
1852 done
1853 return $ret
1854 }
1855
1856 # mail related
1857 testmail() {
1858 declare -gi _seq; _seq+=1
1859 echo "test body" | m mail -s "test mail from $HOSTNAME, $_seq" "${@:-root@localhost}"
1860 # for testing to send from an external address, you can do for example
1861 # -fian@iank.bid -aFrom:ian@iank.bid web-6fnbs@mail-tester.com
1862 # note in exim, you can retry a deferred message
1863 # s exim -M MSG_ID
1864 # MSG_ID is in /var/log/exim4/mainlog, looks like 1ccdnD-0001nh-EN
1865 }
1866
1867 # to test sieve, use below command. for fsf mail, see offlineimap-sync script
1868 # make modifications, then copy to live file, use -eW to actually modify mailbox
1869 #
1870 # Another option is to use sieve-test SCRIPT MAIL_FILE. note,
1871 # sieve-test doesnt know about envelopes, Im not sure if sieve-filter does.
1872
1873 # sieve with output filter. arg is mailbox, like INBOX.
1874 # This depends on dovecot conf, notably mail_location in /etc/dovecot/conf.d/10-mail.conf
1875
1876 _dosieve() {
1877 sieve-filter "$@" 2> >(head; tail) >/tmp/testsieve.log && sed -rn '/^Performed actions:/,/^[^ ]/{/^ /p}' /tmp/testsieve.log | sort | uniq -c
1878 }
1879
1880 # always run this first, edit the test files, then run the following
1881 testsieve() {
1882 _dosieve ~/sieve/maintest.sieve ${1:-INBOX} delete
1883 }
1884 runsieve() {
1885 c ~/sieve; cp personal{test,}.sieve; cp lists{test,}.sieve; cp personalend{test,}.sieve
1886 _dosieve ~/sieve/main.sieve -eW ${1:-INBOX} delete
1887 }
1888
1889 # mail related
1890 testexim() {
1891 # testmail above calls sendmail, which is a link to exim/postfix.
1892 # its docs dont say a way of adding an argument
1893 # to sendmail to turn on debug output. We could make a wrapper, but
1894 # that is a pain. Exim debug args are documented here:
1895 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1896 #
1897 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-building_and_installing_exim.html
1898 # note, for exim daemon, you can turn on debug options by
1899 # adding -d, etc to COMMONOPTIONS in
1900 # /etc/default/exim4
1901 exim -d -t <<'EOF'
1902 From: ian@iankelling.org
1903 To: root@lists0p.fsf.org
1904 Subject: Testing Exim
1905
1906 This is a test message.
1907 EOF
1908 }
1909
1910 # toggle keyboard
1911 tk() {
1912 # based on
1913 # https://askubuntu.com/questions/160945/is-there-a-way-to-disable-a-laptops-internal-keyboard
1914 id=$(xinput --list --id-only 'AT Translated Set 2 keyboard')
1915 if xinput list | grep -F '∼ AT Translated Set 2 keyboard' &>/dev/null; then
1916 echo enabling keyboard
1917 # find the first slave keyboard number, they are all the same in my output.
1918 # if they werent, worst case we would need to save the slave number somewhere
1919 # when it got disabled.
1920 slave=$(xinput list | sed -n 's/.*slave \+keyboard (\([0-9]*\)).*/\1/p' | head -n1)
1921 xinput reattach $id $slave
1922 else
1923 xinput float $id
1924 fi
1925 }
1926
1927 tm() {
1928 # timer in minutes
1929 # --no-config
1930 (sleep $(calc "$* * 60") && mpv --no-config --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1931 }
1932
1933 trg() { transmission-remote-gtk&r; }
1934 trc() {
1935 # example, set global upload limit to 100 kilobytes:
1936 # trc -u 100
1937 TR_AUTH=":$(jq -r .profiles[0].password ~/.config/transmission-remote-gtk/config.json)" transmission-remote transmission.lan -ne "$@"
1938 }
1939
1940
1941 tu() {
1942 local s dir
1943 dir="$(dirname "$1")"
1944 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1945 s=s;
1946 fi
1947 $s teeu "$@"
1948 }
1949
1950 tx() { # toggle set -x, and the prompt so it doesnt spam
1951 if [[ $- == *x* ]]; then
1952 set +x
1953 PROMPT_COMMAND=prompt-command
1954 # disabled due to issue on stretch, running ll we get error. something
1955 # about the DEBUG trap is broken
1956 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1957 # trap 'settitle "$BASH_COMMAND"' DEBUG
1958 # fi
1959 else
1960 # normally, i would just execute these commands in the function.
1961 # however, DEBUG is not inherited, so we need to run it outside a function.
1962 # And we want to run set -x afterwards to avoid spam, so we cram everything
1963 # in here, and then it will run after this function is done.
1964 #PROMPT_COMMAND='trap DEBUG; unset PROMPT_COMMAND; PS1="\w \$ "; set -x'
1965
1966 unset PROMPT_COMMAND
1967 PS1="\w \$ "
1968 set -x
1969 fi
1970 }
1971
1972 psnetns() {
1973 # show all processes in the network namespace $1.
1974 # blank entries appear to be subprocesses/threads
1975 local x netns
1976 netns=$1
1977 ps -w | head -n 1
1978 s find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1979 while read -r l; do
1980 x=$(ps -w --no-headers -p $l);
1981 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1982 done
1983 }
1984
1985 m() { printf "%s\n" "$*"; "$@"; }
1986
1987 vpncmd() {
1988 #m s nsenter -t $(pgrep -f "/usr/sbin/openvpn .* --config /etc/openvpn/.*pia.conf") -n -m "$@"
1989 m s nsenter -t $(pgrep -f "/usr/sbin/openvpn .* --config /etc/openvpn/.*client.conf") -n -m "$@"
1990 }
1991 vpnf() {
1992 vpncmd gksudo -u iank "firefox -no-remote -P vpn" &r
1993 }
1994 vpni() {
1995 vpncmd gksudo -u iank "$*"
1996 }
1997 vpnbash() {
1998 vpncmd bash
1999 }
2000
2001
2002
2003 virshrm() {
2004 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
2005 }
2006
2007 vm-set-listen(){
2008 local t
2009 t=$(mktemp)
2010 local vm=$1
2011 local ip=$2
2012 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
2013 sed -r "s/listen='[^']+/listen='$ip/"> $t
2014 s virsh undefine $vm
2015 s virsh define $t
2016 }
2017
2018
2019 vmshare() {
2020 vm-set-listen $1 0.0.0.0
2021 }
2022
2023
2024 vmunshare() {
2025 vm-set-listen $1 127.0.0.1
2026 }
2027
2028
2029 vpn() {
2030 if [[ -e /lib/systemd/system/openvpn-client@.service ]]; then
2031 local vpn_service=openvpn-client
2032 else
2033 local vpn_service=openvpn
2034 fi
2035
2036 [[ $1 ]] || { echo need arg; return 1; }
2037 journalctl --unit=$vpn_service@$1 -f -n0 &
2038 s systemctl start $vpn_service@$1
2039 # sometimes the ask-password agent does not work and needs a delay.
2040 sleep .5
2041 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=779240
2042 # noticed around 8-2017 after update from around stretch release
2043 # on debian testing, even though the bug is much older.
2044 s systemd-tty-ask-password-agent
2045 }
2046
2047 vpnoff() {
2048 [[ $1 ]] || { echo need arg; return 1; }
2049 if [[ -e /lib/systemd/system/openvpn-client@.service ]]; then
2050 local vpn_service=openvpn-client
2051 else
2052 local vpn_service=openvpn
2053 fi
2054 s systemctl stop $vpn_service@$1
2055 }
2056
2057
2058 vrm() {
2059 virsh destroy $1
2060 virsh undefine $1
2061 }
2062
2063
2064
2065 vspicy() { # usage: VIRSH_DOMAIN
2066 # connect to vms made with virt-install
2067 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
2068 sed -r "s/.*port='([0-9]+).*/\1/")
2069 }
2070
2071 wian() {
2072 cat-new-files /m/4e/INBOX/new
2073 }
2074
2075 wtr() { curl wttr.in/boston; }
2076
2077 xevkb() { xev -event keyboard; }
2078
2079 # * misc stuff
2080
2081 # from curl cheat.sh/:bash_completion
2082 _cheatsh_complete_curl()
2083 {
2084 local cur prev opts
2085 _get_comp_words_by_ref -n : cur
2086
2087 COMPREPLY=()
2088 #cur="${COMP_WORDS[COMP_CWORD]}"
2089 prev="${COMP_WORDS[COMP_CWORD-1]}"
2090 opts="$(curl -s cheat.sh/:list | sed s@^@cheat.sh/@)"
2091
2092 if [[ ${cur} == cheat.sh/* ]] ; then
2093 COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
2094 __ltrim_colon_completions "$cur"
2095 return 0
2096 fi
2097 }
2098 complete -F _cheatsh_complete_curl curl
2099
2100
2101 if [[ $- == *i* ]]; then
2102 # commands to run when bash exits normally
2103 trap "hl" EXIT
2104 fi
2105
2106
2107 # temporary variables to test colorization
2108 # some copied from gentoo /etc/bash/bashrc,
2109 use_color=false
2110 # dircolors --print-database uses its own built-in database
2111 # instead of using /etc/DIR_COLORS. Try to use the external file
2112 # first to take advantage of user additions.
2113 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
2114 match_lhs=""
2115 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
2116 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
2117 [[ -z ${match_lhs} ]] \
2118 && type -P dircolors >/dev/null \
2119 && match_lhs=$(dircolors --print-database)
2120 # test if our $TERM is in the TERM values in dircolor
2121 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
2122
2123
2124 if ${use_color} && [[ $- == *i* ]]; then
2125
2126 term_bold="$(tput bold)"
2127 term_red="$(tput setaf 1)"
2128 term_green="$(tput setaf 2)"
2129 term_yellow="$(tput setaf 3)"
2130 term_purple="$(tput setaf 5)"
2131 term_nocolor="$(tput sgr0)" # no font attributes
2132
2133 # unused so far. commented for shellcheck
2134 # term_underl="$(tput smul)"
2135 # term_blue="$(tput setaf 4)"
2136 # term_cyan="$(tput setaf 6)"
2137
2138 fi
2139 # Try to keep environment pollution down, EPA loves us.
2140 unset safe_term match_lhs use_color
2141
2142
2143
2144 # * prompt
2145
2146
2147 if [[ $- == *i* ]]; then
2148
2149 # this needs to come before next ps1 stuff
2150 # this stuff needs bash 4, feb 2009,
2151 # old enough to no longer condition on $BASH_VERSION anymore
2152 shopt -s autocd
2153 shopt -s dirspell
2154 PS1='\w'
2155 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
2156 PROMPT_DIRTRIM=2
2157 bind -m vi-command B:shell-backward-word
2158 bind -m vi-command W:shell-forward-word
2159 fi
2160
2161 if [[ $SSH_CLIENT || $SUDO_USER ]]; then
2162 PS1="\h $PS1"
2163 fi
2164
2165 # emacs terminal has problems if this runs slowly,
2166 # so I've thrown a bunch of things at the wall to speed it up.
2167 prompt-command() {
2168 local return=$? # this MUST COME FIRST
2169 local ps_char ps_color
2170 unset IFS
2171 history -a # save history
2172
2173 case $return in
2174 0) ps_color="$term_purple"
2175 ps_char='\$'
2176 ;;
2177 1) ps_color="$term_green"
2178 ps_char="$return \\$"
2179 ;;
2180 *) ps_color="$term_yellow"
2181 ps_char="$return \\$"
2182 ;;
2183 esac
2184 if [[ ! -O . ]]; then # not owner
2185 if [[ -w . ]]; then # writable
2186 ps_color="$term_bold$term_red"
2187 else
2188 ps_color="$term_bold$term_green"
2189 fi
2190 fi
2191
2192 # faster than sourceing the file im guessing
2193 eval $(< /dev/shm/iank-status)
2194 if [[ ! $SSH_CLIENT && $MAIL_HOST != "$HOSTNAME" ]]; then
2195 ps_char="@ $ps_char"
2196 fi
2197 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$term_nocolor\] "
2198 }
2199 PROMPT_COMMAND=prompt-command
2200
2201 settitle () {
2202 if [[ $TERM == screen* ]]; then
2203 local title_escape="\033]..2;"
2204 else
2205 local title_escape="\033]0;"
2206 fi
2207 if [[ $0 != prompt-command ]]; then
2208 echo -ne "$title_escape$USER@$HOSTNAME ${PWD/#$HOME/~} "
2209 printf "%s" "$*"
2210 echo -ne "\007"
2211 fi
2212 }
2213
2214 # for titlebar.
2215 # condition from the screen man page i think.
2216 # note: duplicated in tx()
2217 # disabled. see note in tx
2218 # if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
2219 # trap 'settitle "$BASH_COMMAND"' DEBUG
2220 # else
2221 # trap DEBUG
2222 # fi
2223
2224 fi
2225
2226 reset-konsole() {
2227 # we also have a file in /a/c/...konsole...
2228 local f=$HOME/.config/konsolerc
2229 setini DefaultProfile profileian.profile "Desktop Entry" $f
2230 setini Favorites profileian.profile "Favorite Profiles" $f
2231 setini ShowMenuBarByDefault false KonsoleWindow $f
2232 setini TabBarPosition Top TabBar $f
2233 }
2234
2235 reset-sakura() {
2236 while -r read k v; do
2237 # shellcheck disable=SC2154
2238 setini $k $v sakura /a/c/subdir_files/.config/sakura/sakura.conf
2239 done <<'EOF'
2240 colorset1_back rgb(33,37,39
2241 less_questions true
2242 audible_bell No
2243 visible_bell No
2244 disable_numbered_tabswitch true
2245 scroll_lines 10000000
2246 scrollbar true
2247 EOF
2248 }
2249
2250 reset-xscreensaver() {
2251 # except for spash, i set these by setting gui options in
2252 # xscreensaver-command -demo
2253 # then finding the corresponding option in .xscreensaver
2254 # spash, i happened to notice in .xscreensaver
2255 #
2256 # dpmsOff, monitor doesnt come back on using old free software supported nvidia card
2257 cat > /home/iank/.xscreensaver <<'EOF'
2258 mode: blank
2259 dpmsEnabled: True
2260 dpmsStandby: 0:02:00
2261 dpmsSuspend: 0:03:00
2262 dpmsOff: 0:00:00
2263 timeout: 0:02:00
2264 lock: True
2265 lockTimeout: 0:03:00
2266 splash: False
2267 EOF
2268
2269 }
2270
2271
2272 # * stuff that makes sense to be at the end
2273 if [[ "$SUDOD" ]]; then
2274 cd "$SUDOD"
2275 unset SUDOD
2276 elif [[ -d /a ]] && [[ $PWD == "$HOME" ]] && [[ $- == *i* ]]; then
2277 cd /a
2278 fi
2279
2280
2281 # best practice
2282 unset IFS
2283
2284
2285 # for mitmproxy to get a newer python.
2286 # commented until i want to use it because it
2287 # noticably slows bash startup
2288 #
2289
2290 mypyenvinit () {
2291 if [[ $EUID == 0 || ! -e ~/.pyenv/bin ]]; then
2292 echo "error: dont be root. make sure pyenv is installed"
2293 return 1
2294 fi
2295 export PATH="$HOME/.pyenv/bin:$PATH"
2296 eval "$(pyenv init -)"
2297 eval "$(pyenv virtualenv-init -)"
2298 }
2299
2300
2301 export GOPATH=$HOME/go
2302 path_add $GOPATH/bin
2303 path_add /usr/local/go/bin
2304
2305 # I have the git repo and a release. either one should work.
2306 # I have both because I was trying to solve an issue that
2307 # turned out to be unrelated.
2308 # ARDUINO_PATH=/a/opt/Arduino/build/linux/work
2309 export ARDUINO_PATH=/a/opt/arduino-1.8.9
2310
2311 # They want to be added to the start, but i think
2312 # that should be avoided unless we really need it.
2313 path_add --end ~/.npm-global
2314
2315 path_add --end $HOME/.cargo/bin
2316
2317 # taken from default changes to bashrc and bash_profile
2318 path_add --end $HOME/.rvm/bin
2319
2320 # shellcheck disable=SC1090
2321 [[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*
2322
2323 export BASEFILE_DIR=/a/bin/fai-basefiles
2324
2325 export ANDROID_HOME=/opt/android
2326
2327 # didnt get drush working, if I did, this seems like the
2328 # only good thing to include for it.
2329 # Include Drush completion.
2330 # if [ -f "/home/ian/.drush/drush.complete.sh" ] ; then
2331 # source /home/ian/.drush/drush.complete.sh
2332 # fi
2333
2334
2335 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
2336 # i added an extra condition as gentoo xorg guide says depending on
2337 # $DISPLAY is fragile.
2338 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
2339 exec startx
2340 fi
2341
2342
2343 # ensure no bad programs appending to this file will have an affect
2344 return 0