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