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