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