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