various 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 # 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='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
572 # List of apps to install/update
573 # Create from existing manually installed apps by doing
574 # fdroidcl search -i, then manually removing
575 # automatically installed/preinstalled apps
576
577 # firefox updater. commented out, firefox depends on nonfree opengl.
578 # de.marmaro.krt.ffupdater
579 # # causes replicant to die on install and go into a boot loop
580 # me.ccrama.redditslide
581 #
582 # # my attempt at recovering from boot loop:
583 # # in that case, boot to recovery (volume up, home button, power, let go of power after samsun logo)
584 # # then
585 # mount /dev/block/mmcblk0p12 /data
586 # cd /data
587 # find -iname '*appname*'
588 # rm -rf FOUND_DIRS
589 # usually good enough to just rm -rf /data/app/APPNAME
590 #
591 # currently broken:
592 #at.bitfire.davdroid
593 fdroid_pkgs=(
594 com.alaskalinuxuser.justnotes
595 com.artifex.mupdfdemo
596 com.fsck.k9
597 com.ichi2.anki
598 com.jmstudios.redmoon
599 com.notecryptpro
600 com.nutomic.syncthingandroid
601 com.termux
602 com.zoffcc.applications.zanavi
603 cz.martykan.forecastie
604 de.danoeh.antennapod
605 im.vector.alpha # riot
606 info.papdt.blackblub
607 me.tripsit.tripmobile
608 net.gaast.giggity
609 net.osmand.plus
610 net.sourceforge.opencamera
611 org.dmfs.tasks # caldav tasks thing
612 org.fdroid.fdroid
613 org.isoron.uhabits
614 org.kde.kdeconnect_tp
615 org.quantumbadger.redreader
616 org.smssecure.smssecure
617 org.fedorahosted.freeotp
618 )
619 # https://forum.xda-developers.com/android/software-hacking/wip-selinux-capable-superuser-t3216394
620 # for maru,
621 #me.phh.superuser
622
623 fdup() {
624 local -A installed updated
625 local p
626 fdroidcl update
627 for p in $(fdroidcl search -i| grep -o "^\S\+"); do
628 installed[$p]=true
629 done
630 for p in $(fdroidcl search -u| grep -o "^\S\+"); do
631 updated[$p]=false
632 done
633 for p in ${fdroid_pkgs[@]}; do
634 ${installed[$p]:-false} || fdroidcl install $p
635 done
636 for p in ${!installed[@]}; do
637 ${updated[$p]:-true} || fdroidcl upgrade $p
638 done
639 }
640
641 firefox-default-profile() {
642 key=Default value=1 section=$1
643 file=/p/c/subdir_files/.mozilla/firefox/profiles.ini
644 sed -ri "/^ *$key/d" "$file"
645 sed -ri "/ *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d};/ *\[$section\]/a $key=$value" "$file"
646 }
647 fdhome() { #firefox default home profile
648 firefox-default-profile Profile0
649 }
650
651 fdwork() {
652 firefox-default-profile Profile4
653 }
654
655 ff() {
656 if type -P firefox &>/dev/null; then
657 firefox "$@"
658 else
659 iceweasel "$@"
660 fi
661 }
662
663
664
665 fn() {
666 firefox -P alt "$@" >/dev/null 2>&1
667 }
668
669
670 fsdiff () {
671 local missing=false
672 local dname="${PWD##*/}"
673 local m="/a/tmp/$dname-missing"
674 local d="/a/tmp/$dname-diff"
675 [[ -e $d ]] && rm "$d"
676 [[ -e $m ]] && rm "$m"
677 local msize=0
678 local fsfile
679 while read -r line; do
680 fsfile="$1${line#.}"
681 if [[ -e "$fsfile" ]]; then
682 md5diff "$line" "$fsfile" && tee -a "/a/tmp/$dname-diff" <<< "$fsfile $line"
683 else
684 missing=true
685 echo "$line" >> "$m"
686 msize=$((msize + 1))
687 fi
688 done < <(find -type f )
689 if $missing; then
690 echo "$m"
691 (( msize <= 100 )) && cat $m
692 fi
693 }
694 fsdiff-test() {
695 # expected output, with different tmp dirs
696 # /tmp/tmp.HDPbwMqdC9/c/d ./c/d
697 # /a/tmp/tmp.qLDkYxBYPM-missing
698 # ./b
699 cd $(mktemp -d)
700 echo ok > a
701 echo nok > b
702 mkdir c
703 echo ok > c/d
704 local x=$(mktemp -d)
705 mkdir $x/c
706 echo different > $x/c/d
707 echo ok > $x/a
708 fsdiff $x
709 }
710 rename-test() {
711 # test whether missing files were renamed, generally for use with fsdiff
712 # $1 = fsdiff output file, $2 = directory to compare to. pwd = fsdiff dir
713 # echos non-renamed files
714 local x y found
715 unset sums
716 for x in "$2"/*; do
717 { sums+=( "$(md5sum < "$x")" ) ; } 2>/dev/null
718 done
719 while read -r line; do
720 { missing_sum=$(md5sum < "$line") ; } 2>/dev/null
721 renamed=false
722 for x in "${sums[@]}"; do
723 if [[ $missing_sum == "$x" ]]; then
724 renamed=true
725 break
726 fi
727 done
728 $renamed || echo "$line"
729 done < "$1"
730 return 0
731 }
732
733 feh() {
734 # F = fullscren, z = random, Z = auto zoom
735 command feh -FzZ "$@"
736 }
737
738 # mail related
739 frozen() {
740 rm -rf /tmp/frozen
741 s mailq |gr frozen|awk '{print $3}' | while read -r id; do
742 s exim -Mvl $id
743 echo
744 s exim -Mvh $id
745 echo
746 s exim -Mvb $id
747 echo -e '\n\n##############################\n'
748 done | tee -a /tmp/frozen
749 }
750 frozenrm() {
751 local ids=()
752 while read -r line; do
753 printf '%s\n' "$line"
754 ids+=($(printf '%s\n' "$line" |gr frozen|awk '{print $3}'))
755 done < <(s mailq)
756 echo "sleeping for 2 in case you change your mind"
757 sleep 2
758 s exim -Mrm "${ids[@]}"
759 }
760
761 funce() {
762 # like -e for functions. returns on error.
763 # at the end of the function, disable with:
764 # trap ERR
765 trap 'echo "${BASH_COMMAND:+BASH_COMMAND=\"$BASH_COMMAND\" }
766 ${FUNCNAME:+FUNCNAME=\"$FUNCNAME\" }${LINENO:+LINENO=\"$LINENO\" }\$?=$?"
767 trap ERR
768 return' ERR
769 }
770
771
772 fw() {
773 firefox -P default "$@" >/dev/null 2>&1
774 }
775
776 getdir () {
777 local help="Usage: getdir [--help] PATH
778 Output the directory of PATH, or just PATH if it is a directory."
779 if [[ $1 == --help ]]; then
780 echo "$help"
781 return 0
782 fi
783 if [[ $# -ne 1 ]]; then
784 echo "getdir error: expected 1 argument, got $#"
785 return 1
786 fi
787 if [[ -d $1 ]]; then
788 echo "$1"
789 else
790 local dir="$(dirname "$1")"
791 if [[ -d $dir ]]; then
792 echo "$dir"
793 else
794 echo "getdir error: directory does not exist"
795 return 1
796 fi
797 fi
798 }
799
800 git_empty_branch() { # start an empty git branch. carefull, it deletes untracked files.
801 [[ $# == 1 ]] || { echo 'need a branch name!'; return 1;}
802 local gitroot
803 gitroot || return 1 # function to set gitroot
804 builtin cd "$gitroot"
805 git symbolic-ref HEAD refs/heads/$1
806 rm .git/index
807 git clean -fdx
808 }
809
810 gitroot() {
811 local help="Usage: gitroot [--help]
812 Print the full path to the root of the current git repo
813
814 Handles being within a .git directory, unlike git rev-parse --show-toplevel,
815 and works in older versions of git which did not have that."
816 if [[ $1 == --help ]]; then
817 echo "$help"
818 return
819 fi
820 local p=$(git rev-parse --git-dir) || { echo "error: not in a git repo" ; return 1; }
821 [[ $p != /* ]] && p=$PWD
822 echo "${p%%/.git}"
823 }
824
825 gitian() {
826 git config user.email ian@iankelling.org
827 }
828
829 gmacs() {
830 # quit will prompt if the program crashes.
831 gdb -ex=r -ex=quit --args emacs "$@"; r;
832 }
833
834 gdkill() {
835 # kill the emacs daemon
836 pk1 emacs --daemon
837 }
838
839 gse() {
840 git send-email --notes '--envelope-sender=<ian@iankelling.org>' \
841 --suppress-cc=self "$@"
842 }
843
844 gr() {
845 grep -iIP --color=auto "$@"
846 }
847
848 grr() {
849 if [[ ${#@} == 1 ]]; then
850 grep -riIP --color=auto "$@" .
851 else
852 grep -riIP --color=auto "$@"
853 fi
854 }
855
856 hstatus() {
857 # do git status on published repos
858 cd /a/bin/githtml
859 for x in !(forks) forks/* ian-specific/*; do
860 cd `readlink -f $x`/..
861 hr
862 echo $x
863 i status
864 cd /a/bin/githtml
865 done
866 }
867
868 hl() { # history limit. Write extra history to archive file.
869 # todo: this is not working or not used currently
870 local max_lines linecount tempfile prune_lines x
871 local harchive="${HISTFILE}_archive"
872 for x in "$HISTFILE" "$harchive"; do
873 [[ -e $x ]] || { touch "$x" && echo "notice from hl(): creating $x"; }
874 if [[ ! $x || ! -e $x || ! -w $x || $(stat -c "%u" "$x") != $EUID ]]; then
875 echo "error in hl: history file \$x:$x no good"
876 return 1
877 fi
878 done
879 history -a # save history
880 max_lines=$HISTFILELINES
881 [[ $max_lines =~ ^[0-9]+$ ]] || { echo "error in hl: failed to get max line count"; return 1; }
882 linecount=$(wc -l < $HISTFILE) # pipe so it doesn't output a filename
883 [[ $linecount =~ ^[0-9]+$ ]] || { echo "error in hl: wc failed"; return 1; }
884 if (($linecount > $max_lines)); then
885 prune_lines=$(($linecount - $max_lines))
886 head -n $prune_lines "$HISTFILE" >> "$harchive" \
887 && sed --follow-symlinks -ie "1,${prune_lines}d" $HISTFILE
888 fi
889 }
890
891 hr() { # horizontal row. used to break up output
892 printf "$(tput setaf 5)â–ˆ$(tput sgr0)%.0s" $(seq ${COLUMNS:-60})
893 echo
894 }
895
896 hrcat() { local f; for f; do [[ -f $f ]] || continue; hr; echo "$f"; cat "$f"; done }
897
898
899 i() { git "$@"; }
900 # modified from ~/local/bin/git-completion.bash
901 # other completion commands are mostly taken from bash_completion package
902 complete -o bashdefault -o default -o nospace -F _git i 2>/dev/null \
903 || complete -o default -o nospace -F _git i
904
905 if ! type service &>/dev/null; then
906 service() {
907 echo actually running: systemctl $2 $1
908 systemctl $2 $1
909 }
910 fi
911
912 ic() {
913 # fast commit all
914 git commit -am "$*"
915 }
916
917 idea() {
918 /a/opt/idea-IC-163.7743.44/bin/idea.sh "$@" &r
919 }
920
921 ifn() {
922 # insensitive find
923 find -L . -not \( -name .svn -prune -o -name .git -prune \
924 -o -name .hg -prune -o -name .editor-backups -prune \
925 -o -name .undo-tree-history -prune \) -iname "*$**" 2>/dev/null
926 }
927
928
929 if [[ $OS == Windows_NT ]]; then
930 # cygstart wrapper
931 cs() {
932 cygstart "$@" &
933 }
934 xp() {
935 explorer.exe .
936 }
937 # launch
938 o() {
939 local x=(*$1*)
940 (( ${#x[#]} > 1 )) && { echo "warning ${#x[#]} matches found"; sleep 1; }
941 cygstart *$1* &
942 }
943 else
944 o() {
945 if type gvfs-open &> /dev/null ; then
946 gvfs-open "$@"
947 else
948 xdg-open "$@"
949 fi
950 # another alternative is run-mailcap
951 }
952 fi
953
954 ipdrop() {
955 s iptables -A INPUT -s $1 -j DROP
956 }
957
958 net-dev-info() {
959 e "lspci -nnk|gr -iA2 net"
960 lspci -nnk|gr -iA2 net
961 hr
962 e "s lshw -C network"
963 hr
964 s lshw -C network
965
966 }
967
968 istext() {
969 grep -Il "" "$@" &>/dev/null
970 }
971
972 jtail() {
973 journalctl -n 10000 -f "$@" | grep -Evi "^(\S+\s+){4}(sudo|sshd|cron)"
974 }
975
976 kff() { # keyboardio firmware flash
977 pushd /a/opt/sketches/Model01-Firmware
978 yes $'\n' | make flash
979 popd
980 }
981
982 l() {
983 if [[ $PWD == /[iap] ]]; then
984 command ls -A --color=auto -I lost+found "$@"
985 else
986 command ls -A --color=auto "$@"
987 fi
988 }
989
990
991 lcn() { locate -i "*$**"; }
992
993 lld() { ll -d "$@"; }
994
995 low() { # make filenames lowercase, remove bad chars
996 local f new
997 for f in "$@"; do
998 new="${f,,}" # downcase
999 new="${new//[^[:alnum:]._-]/_}" # sub bad chars
1000 new="${new#"${new%%[[:alnum:]]*}"}" # remove leading/trailing non-alnum
1001 new="${new%"${new##*[[:alnum:]]}"}"
1002 # remove bad underscores, like __ and _._
1003 new=$(echo $new | sed -r 's/__+/_/g;s/_+([.-])|([.-])_+/\1/g')
1004 safe_rename "$f" "$new" || return 1
1005 done
1006 return 0
1007 }
1008
1009 lower() { # make first letter of filenames lowercase.
1010 local x
1011 for x in "$@"; do
1012 if [[ ${x::1} == [A-Z] ]]; then
1013 y=$(tr "[A-Z]" "[a-z]" <<<"${x::1}")"${x:1}"
1014 safe_rename "$x" "$y" || return 1
1015 fi
1016 done
1017 }
1018
1019
1020 k() { # history search
1021 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | tail -n 80;
1022 }
1023
1024 ks() { # history search
1025 grep -P --binary-files=text "$@" ${HISTFILE:-~/.bash_history} | uniq;
1026 }
1027
1028
1029 make-targets() {
1030 # show make targets, via http://stackoverflow.com/questions/3063507/list-goals-targets-in-gnu-make
1031 make -qp | awk -F':' '/^[a-zA-Z0-9][^$#\/\t=]*:([^=]|$)/ {split($1,A,/ /);for(i in A)print A[i]}'
1032 }
1033
1034 mbenable() {
1035 mb=$1
1036 dst=/m/4e/$1
1037 src=/m/md/$1
1038 set -x
1039 mv -T $src $dst || { set +x; return 1; }
1040 ln -s -T $dst $src
1041 /a/exe/lnf /p/.mu ~
1042 mu index --maildir=/m/4e
1043 set +x
1044 }
1045 mbdisable() {
1046 mb=$1
1047 dst=/m/md/$1
1048 src=/m/4e/$1
1049 set -x
1050 if [[ -L $dst ]]; then rm $dst; fi
1051 mv -T $src $dst
1052 set +x
1053 }
1054
1055 mdt() {
1056 markdown -o /tmp/mdtest.html "$1"
1057 firefox /tmp/mdtest.html
1058 }
1059
1060
1061 mkc() {
1062 mkdir "$1"
1063 c "$1"
1064 }
1065
1066 mkt() { # mkdir and touch file
1067 local path="$1"
1068 mkdir -p "$(dirname "$path")"
1069 touch "$path"
1070 }
1071
1072 mkdir() { command mkdir -p "$@"; }
1073
1074 mo() { xset dpms force off; } # monitor off
1075
1076 otp() {
1077 oathtool --totp -b "$@" | xclip -selection clipboard
1078 }
1079
1080 # pithosfly is broken due to bitrot.
1081 pithos() {
1082 cd /
1083 export PYTHONPATH=/a/opt/Pithosfly
1084 python3 -m pithos&r
1085 }
1086
1087 pakaraoke() {
1088 # from http://askubuntu.com/questions/456021/remove-vocals-from-mp3-and-get-only-instrumentals
1089 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
1090 }
1091
1092
1093 pfind() { #find *$1* in $PATH
1094 [[ $# != 1 ]] && { echo requires 1 argument; return 1; }
1095 local pathArray
1096 IFS=: pathArray=($PATH); unset IFS
1097 find "${pathArray[@]}" -iname "*$1*"
1098 }
1099
1100 pk1() {
1101 local pid
1102 pid=($(pgrep -f "$*"))
1103 case ${#pid[@]} in
1104 1)
1105 ps -F $pid
1106 m kill $pid
1107 ;;
1108 0) echo "no pid found" ;;
1109 *)
1110 ps -F ${pid[@]}
1111 ;;
1112 esac
1113 }
1114
1115 pick-trash() {
1116 # trash-restore lists everything that has been trashed at or below CWD
1117 # This picks out files just in CWD, not subdirectories,
1118 # which also match grep $1, usually use $1 for a time string
1119 # which you get from running restore-trash once first
1120 local name x ask
1121 local nth=1
1122 # last condition is to not ask again for ones we skipped
1123 while name="$( echo | restore-trash | gr "$PWD/[^/]\+$" | gr "$1" )" \
1124 && [[ $name ]] && (( $(wc -l <<<"$name") >= nth )); do
1125 name="$(echo "$name" | head -n $nth | tail -n 1 )"
1126 read -p "$name [Y/n] " ask
1127 if [[ ! $ask || $ask == [Yy] ]]; then
1128 x=$( echo "$name" | gr -o "^\s*[0-9]*" )
1129 echo $x | restore-trash > /dev/null
1130 elif [[ $ask == [Nn] ]]; then
1131 nth=$((nth+1))
1132 else
1133 return
1134 fi
1135 done
1136 }
1137
1138 ping8() { ping 8.8.8.8; }
1139
1140 pub() {
1141 rld /a/h/_site/ li:/var/www/iankelling.org/html
1142 }
1143
1144 pubip() { curl -4s https://icanhazip.com; }
1145 whatismyip() { pubip; }
1146
1147 pumpa() {
1148 # fixes the menu bar in xmonad. this won\'t be needed when xmonad
1149 # packages catches up on some changes in future (this is written in
1150 # 4/2017)
1151 #
1152 # geekosaur: so you'll want to upgrade to xmonad 0.13 or else use a
1153 # locally modified XMonad.Hooks.ManageDocks that doesn't set the
1154 # work area; turns out it's impossible to set correctly if you are
1155 # not a fully EWMH compliant desktop environment
1156 #
1157 # geekosaur: chrome shows one failure mode, qt/kde another, other
1158 # gtk apps a third, ... I came up with a setting that works for me
1159 # locally but apparently doesn't work for others, so we joined the
1160 # other tiling window managers in giving up on setting it at all
1161 #
1162 xprop -root -remove _NET_WORKAREA
1163 command pumpa &r
1164 }
1165
1166
1167 pwgen() {
1168 # -m = min length
1169 # -x = max length
1170 # -t = print pronunciation
1171 apg -m 12 -x 16 -t
1172 }
1173
1174 pwlong() {
1175 # -M CLN = use Caps, Lowercase, Numbers
1176 # -n 1 = 1 password
1177 # -a 1 = use random instead of pronounceable algorithm
1178 apg -m 50 -x 70 -n 1 -a 1 -M CLN
1179 }
1180
1181
1182 q() { # start / launch a program in the backround and redir output to null
1183 "$@" &> /dev/null &
1184 }
1185
1186 r() {
1187 exit "$@" 2>/dev/null
1188 }
1189
1190 rbpipe() { rbt post -o --diff-filename=- "$@"; }
1191 rbp() { rbt post -o "$@"; }
1192
1193 rl() {
1194 # rsync, root is required to keep permissions right.
1195 # rsync --archive --human-readable --verbose --itemize-changes --checksum \(-ahvic\) \
1196 # --no-times --delete
1197 # basically, make an exact copy, use checksums instead of file times to be more accurate
1198 rsync -ahvic --delete "$@"
1199 }
1200 rld() {
1201 # like rlu, but don't delete files on the target end which
1202 # do not exist on the original end.
1203 rsync -ahvic "$@"
1204 }
1205 complete -F _rsync -o nospace rld rl rlt
1206
1207 rlt() {
1208 # rl without preserving modification time.
1209 rsync -ahvic --delete --no-t "$@"
1210 }
1211
1212 rlu() { # [OPTS] HOST PATH
1213 # eg. rlu -opts frodo /testpath
1214 # relative paths will expanded with readlink -f.
1215 # useful for selectively sending dirs which have been synced with unison,
1216 # where the path is the same on both hosts.
1217 opts=("${@:1:$#-2}") # 1 to last -2
1218 path="${@:$#}" # last
1219 host="${@:$#-1:1}" # last -1
1220 if [[ $path == .* ]]; then
1221 path=$(readlink -f $path)
1222 fi
1223 # rync here uses checksum instead of time so we don't mess with
1224 # unison relying on time as much. g is for group, same reason
1225 # to keep up with unison.
1226 s rsync -rlpchviog --relative "${opts[@]}" "$path" "root@$host:/";
1227 }
1228
1229 # only run on desktop. simpler to keep this on one system.
1230 r2eadd() { # usage: name url
1231 # initial setup of rss2email:
1232 # r2e new r2e@iankelling.org
1233 # that initializes files, and sets default email.
1234 # symlink to the config doesn't work, so I copied it to /p/c
1235 # and then use cli option to specify explicit path.
1236 # Only option changed from default config is to set
1237 # force-from = True
1238 #
1239 # or else for a few feeds, the from address is set by the feed, and
1240 # if I fail delivery, then I send a bounce message to that from
1241 # address, which makes me be a spammer.
1242
1243 r2e add $1 "$2" $1@r2e.iankelling.org
1244 # get up to date and don't send old entries now:
1245 r2e run --no-send $1
1246 }
1247 r2e() { command r2e -d /p/c/rss2email.json -c /p/c/rss2email.cfg "$@"; }
1248
1249 rspicy() { # usage: HOST DOMAIN
1250 # connect to spice vm remote host. use vspicy for local host
1251 local port=$(ssh $1<<EOF
1252 sudo virsh dumpxml $2|grep "<graphics.*type='spice'" | \
1253 sed -rn "s/.*port='([0-9]+).*/\1/p"
1254 EOF
1255 )
1256 if [[ $port ]]; then
1257 spicy -h $1 -p $port
1258 else
1259 echo "error: no port found. check that the domain is running."
1260 fi
1261 }
1262
1263 rmstrips() {
1264 ssh fencepost head -n 300 /gd/gnuorg/EventAndTravelInfo/rms-current-trips.txt
1265 }
1266
1267 s() {
1268 # background
1269 # I use a function because otherwise we can't use in a script,
1270 # can't assign to variable.
1271 #
1272 # note: gksudo is recommended for X apps because it does not set the
1273 # home directory to the same, and thus apps writing to ~ fuck things up
1274 # with root owned files.
1275 #
1276 if [[ $EUID != 0 || $1 == -* ]]; then
1277 SUDOD="$PWD" sudo -i "$@"
1278 else
1279 "$@"
1280 fi
1281 }
1282
1283 safe_rename() { # warn and don't rename if file exists.
1284 # mv -n exists, but it's silent
1285 if [[ $# != 2 ]]; then
1286 echo safe_rename error: $# args, need 2 >2
1287 return 1
1288 fi
1289 if [[ $1 != $2 ]]; then # yes, we want to silently ignore this
1290 if [[ -e $2 || -L $2 ]]; then
1291 echo "Cannot rename $1 to $2 as it already exists."
1292 else
1293 mv -vi "$1" "$2"
1294 fi
1295 fi
1296 }
1297
1298
1299 sb() { # sudo bash -c
1300 # use sb instead of s is for sudo redirections,
1301 # eg. sb 'echo "ok fine" > /etc/file'
1302 local SUDOD="$PWD"
1303 sudo -i bash -c "$@"
1304 }
1305 complete -F _root_command s sb
1306
1307 scssl() {
1308 # s gem install scss-lint
1309 pushd /a/opt/thoughtbot-guides
1310 git pull --stat
1311 popd
1312 scss-lint -c /a/opt/thoughtbot-guides/style/sass/.scss-lint.yml "$@"
1313 }
1314
1315 ser() {
1316 local s; [[ $EUID != 0 ]] && s=sudo
1317 if type -p systemctl &>/dev/null; then
1318 $s systemctl $1 $2
1319 else
1320 $s service $2 $1
1321 fi
1322 }
1323
1324 setini() { # set a value in a .ini style file
1325 key="$1" value="$2" section="$3" file="$4"
1326 if [[ -s $file ]]; then
1327 sed -ri -f - "$file" <<EOF
1328 # remove existing keys
1329 / *\[$section\]/,/^ *\[[^]]+\]/{/^\s*$key[[:space:]=]/d}
1330 # add key
1331 /^\s*\[$section\]/a $key=$value
1332 # from section to eof, do nothing
1333 /^\s*\[$section\]/,\$b
1334 # on the last line, if we haven't found section yet, add section and key
1335 \$a [$section]\\
1336 $key=$value
1337 EOF
1338 else
1339 cat >"$file" <<EOF
1340 [$section]
1341 $key=$value
1342 EOF
1343 fi
1344 }
1345
1346 sgo() { # service go
1347 service=$1
1348 ser restart $service || return 1
1349 if type -p systemctl &>/dev/null; then
1350 ser enable $service
1351 fi
1352 }
1353
1354
1355 shellck() {
1356 # 2086 = unquoted $var
1357 # 2046 = unquoted $(cmd)
1358 # i had -x as an arg, but debian testing(stretch) doesn\'t support it
1359 shellcheck -e 2086,2046,2068,2006,2119 "$@"
1360 }
1361
1362 skaraoke() {
1363 local tmp out
1364 in="$1"
1365 out=${2:-${1%.*}.sh}
1366 tmp=$(mktemp -d)
1367 script -t -c "mpv --no-config --no-resume-playback --no-terminal --no-audio-display '$1'" $tmp/typescript 2>$tmp/timing
1368 # todo, the current sleep seems pretty good, but it
1369 # would be nice to have an empirical measurement, or
1370 # some better wait to sync up.
1371 #
1372 # note: --loop-file=no prevents it from hanging if you have that
1373 # set to inf the mpv config.
1374 # --loop=no prevents it from exit code 3 due to stdin if you
1375 # had it set to inf in mpv config.
1376 #
1377 # args go to mpv, for example --volume=80, 50%
1378 cat >$out <<EOFOUTER
1379 #!/bin/bash
1380 trap "trap - TERM && kill 0" INT TERM ERR; set -e
1381 ( sleep .2; scriptreplay <( cat <<'EOF'
1382 $(cat $tmp/timing)
1383 EOF
1384 ) <( cat <<'EOF'
1385 $(cat $tmp/typescript)
1386 EOF
1387 ))&
1388 base64 -d - <<'EOF'| mpv --loop=no --loop-file=no --no-terminal --no-audio-display "\$@" -
1389 $(base64 "$1")
1390 EOF
1391 kill 0
1392 EOFOUTER
1393 rm -r $tmp
1394 chmod +x $out
1395 }
1396
1397 slog() {
1398 # log with script. timing is $1.t and script is $1.s
1399 # -l to save to ~/typescripts/
1400 # -t to add a timestamp to the filenames
1401 local logdir do_stamp arg_base
1402 (( $# >= 1 )) || { echo "arguments wrong"; return 1; }
1403 logdir="/a/dt/"
1404 do_stamp=false
1405 while getopts "lt" option
1406 do
1407 case $option in
1408 l ) arg_base=$logdir ;;
1409 t ) do_stamp=true ;;
1410 esac
1411 done
1412 shift $(($OPTIND - 1))
1413 arg_base+=$1
1414 [[ -e $logdir ]] || mkdir -p $logdir
1415 $do_stamp && arg_base+=$(date +%F.%T%z)
1416 script -t $arg_base.s 2> $arg_base.t
1417 }
1418 splay() { # script replay
1419 #logRoot="$HOME/typescripts/"
1420 #scriptreplay "$logRoot$1.t" "$logRoot$1.s"
1421 scriptreplay "$1.t" "$1.s"
1422 }
1423
1424 spend() {
1425 s systemctl suspend
1426 }
1427
1428 sr() {
1429 # sudo redo. be aware, this command may not work right on strange distros or earlier software
1430 if [[ $# == 0 ]]; then
1431 sudo -E bash -c -l "$(history -p '!!')"
1432 else
1433 echo this command redos last history item. no argument is accepted
1434 fi
1435 }
1436
1437 srm () {
1438 # with -ll, less secure but faster.
1439 command srm -ll "$@"
1440 }
1441
1442 srun() {
1443 scp $2 $1:/tmp
1444 ssh $1 /tmp/${2##*/} "${@:2}"
1445 }
1446
1447 sss() { # ssh solo
1448 ssh -oControlMaster=no -oControlPath=/ "$@"
1449 }
1450 ssk() {
1451 local -a opts=()
1452 while [[ $1 == -* ]]; do
1453 opts+=("$1")
1454 shift
1455 done
1456 m pkill -f "^ssh: /tmp/ssh_mux_${USER}_${1#*@}_22_"
1457 m ssh "${opts[@]}" "$@"
1458 }
1459
1460 swap() {
1461 local tmp
1462 tmp=$(mktemp)
1463 mv $1 $tmp
1464 mv $2 $1
1465 mv $tmp $2
1466 }
1467
1468 t() {
1469 local x
1470 local -a args
1471 if type -t trash-put >/dev/null; then
1472 # skip args that don't exist, or else trash-put will have an error
1473 for x in "$@"; do
1474 if [[ -e $x || -L $x ]]; then
1475 args+=("$x")
1476 fi
1477 done
1478 [[ ! ${args[@]} ]] || trash-put "${args[@]}"
1479 else
1480 rm -rf "$@"
1481 fi
1482 }
1483
1484
1485 tclock() {
1486 clear
1487 date +%l:%_M
1488 len=60
1489 # this goes to full width
1490 #len=${1:-$((COLUMNS -7))}
1491 x=1
1492 while true; do
1493 if (( x == len )); then
1494 end=true
1495 d="$(date +%l:%_M) "
1496 else
1497 end=false
1498 d=$(date +%l:%M:%_S)
1499 fi
1500 echo -en "\r"
1501 echo -n "$d"
1502 for ((i=0; i<x; i++)); do
1503 if (( i % 6 )); then
1504 echo -n _
1505 else
1506 echo -n .
1507 fi
1508 done
1509 if $end; then
1510 echo
1511 x=1
1512 else
1513 x=$((x+1))
1514 fi
1515 sleep 5
1516 done
1517 }
1518
1519
1520 te() {
1521 # test existence / exists
1522 local ret=0
1523 for x in "$@"; do
1524 [[ -e "$x" || -L "$x" ]] || ret=1
1525 done
1526 return $ret
1527 }
1528
1529 # mail related
1530 testmail() {
1531 declare -gi _seq; _seq+=1
1532 echo "test body" | m mail -s "test mail from $HOSTNAME, $_seq" "${@:-root@localhost}"
1533 # for testing to send from an external address, you can do for example
1534 # -fian@iank.bid -aFrom:ian@iank.bid web-6fnbs@mail-tester.com
1535 # note in exim, you can retry a deferred message
1536 # s exim -M MSG_ID
1537 # MSG_ID is in /var/log/exim4/mainlog, looks like 1ccdnD-0001nh-EN
1538 }
1539
1540 # to test sieve, use below command. for fsf mail, see fsf-get-mail script.
1541 # make modifications, then copy to live file, use -eW to actually modify mailbox
1542 # cp /p/c/subdir_files/sieve/personal{test,}.sieve; testsievelist -eW INBOX
1543 #
1544 # Another option is to use sieve-test SCRIPT MAIL_FILE. note,
1545 # sieve-test doesn't know about envelopes, I'm not sure if sieve-filter does.
1546
1547 # sieve with output filter. arg is mailbox, like INBOX.
1548 # This depends on dovecot conf, notably mail_location in /etc/dovecot/conf.d/10-mail.conf
1549
1550 testsievelist() {
1551 sieve-filter ~/sieve/maintest.sieve "$@" >/tmp/testsieve.log 2> >(tail) && sed -rn '/^Performed actions:/{n;n;p}' /tmp/testsieve.log | sort -u
1552 }
1553
1554
1555 # mail related
1556 # plain sieve
1557 testsieve() {
1558 sieve-filter ~/sieve/main.sieve "$@"
1559 }
1560
1561 # mail related
1562 testexim() {
1563 # testmail above calls sendmail, which is a link to exim/postfix.
1564 # it's docs don't say a way of adding an argument
1565 # to sendmail to turn on debug output. We could make a wrapper, but
1566 # that is a pain. Exim debug args are documented here:
1567 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-the_exim_command_line.html
1568 #
1569 # http://www.exim.org/exim-html-current/doc/html/spec_html/ch-building_and_installing_exim.html
1570 # note, for exim daemon, you can turn on debug options by
1571 # adding -d, etc to COMMONOPTIONS in
1572 # /etc/default/exim4
1573 # for testing external mail, you need the to address as final cmdline arg
1574 exim -d+tls -t <<'EOF'
1575 From: root@frodo.lan
1576 To: ian@mail.iankelling.org
1577 Subject: Testing Exim
1578
1579 This is a test message.
1580 EOF
1581 }
1582
1583 tm() {
1584 # timer in minutes
1585 # --no-config
1586 (sleep $(calc "$@ * 60") && mpv --no-config --volume 50 /a/bin/data/alarm.mp3) > /dev/null 2>&1 &
1587 }
1588
1589 trg() { transmission-remote-gtk&r; }
1590 trc() {
1591 # example, set global upload limit to 100 kilobytes:
1592 # trc -u 100
1593 TR_AUTH=":$(jq -r .profiles[0].password ~/.config/transmission-remote-gtk/config.json)" transmission-remote transmission.lan -ne "$@"
1594 }
1595
1596
1597 tu() {
1598 local s;
1599 local dir="$(dirname "$1")"
1600 if [[ -e $1 && ! -w $1 || ! -w $(dirname "$1") ]]; then
1601 s=s;
1602 fi
1603 $s teeu "$@"
1604 }
1605
1606 tx() { # toggle set -x, and the prompt so it doesn't spam
1607 if [[ $- == *x* ]]; then
1608 set +x
1609 PROMPT_COMMAND=prompt-command
1610 else
1611 unset PROMPT_COMMAND
1612 PS1="\w \$ "
1613 set -x
1614 fi
1615 }
1616
1617 psnetns() {
1618 # show all processes in the network namespace $1.
1619 # blank entries appear to be subprocesses/threads
1620 local x netns
1621 netns=$1
1622 ps -w | head -n 1
1623 s find -L /proc/[1-9]*/task/*/ns/net -samefile /run/netns/$netns | cut -d/ -f5 | \
1624 while read l; do
1625 x=$(ps -w --no-headers -p $l);
1626 if [[ $x ]]; then echo "$x"; else echo $l; fi;
1627 done
1628 }
1629
1630 m() { printf "%s\n" "$*"; "$@"; }
1631
1632
1633 vpncmd() {
1634 m s nsenter -t $(pgrep -f "/usr/sbin/openvpn .* --config /etc/openvpn/client/client.conf") -n -m "$@"
1635 }
1636 vpnf() {
1637 vpncmd gksudo -u ian "firefox -no-remote -P firefox-main-profile" &r
1638 }
1639 vpnbash() {
1640 vpncmd bash
1641 }
1642
1643
1644
1645 virshrm() {
1646 for x in "$@"; do virsh destroy "$x"; virsh undefine "$x"; done
1647 }
1648
1649 vm-set-listen(){
1650 local t=$(mktemp)
1651 local vm=$1
1652 local ip=$2
1653 s virsh dumpxml $vm | sed -r "s/(<listen.*address=')([^']+)/\1$ip/" | \
1654 sed -r "s/listen='[^']+/listen='$ip/"> $t
1655 s virsh undefine $vm
1656 s virsh define $t
1657 }
1658
1659
1660 vmshare() {
1661 vm-set-listen $1 0.0.0.0
1662 }
1663
1664
1665 vmunshare() {
1666 vm-set-listen $1 127.0.0.1
1667 }
1668
1669
1670 vpn() {
1671 if [[ -e /lib/systemd/system/openvpn-client@.service ]]; then
1672 local vpn_service=openvpn-client
1673 else
1674 local vpn_service=openvpn
1675 fi
1676
1677 [[ $1 ]] || { echo need arg; return 1; }
1678 journalctl --unit=$vpn_service@$1 -f -n0 &
1679 s systemctl start $vpn_service@$1
1680 # sometimes the ask-password agent does not work and needs a delay.
1681 sleep .5
1682 # https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=779240
1683 # noticed around 8-2017 after update from around stretch release
1684 # on debian testing, even though the bug is much older.
1685 s systemd-tty-ask-password-agent
1686 }
1687
1688 vpnoff() {
1689 [[ $1 ]] || { echo need arg; return 1; }
1690 if [[ -e /lib/systemd/system/openvpn-client@.service ]]; then
1691 local vpn_service=openvpn-client
1692 else
1693 local vpn_service=openvpn
1694 fi
1695 s systemctl stop $vpn_service@$1
1696 }
1697
1698
1699 vrm() {
1700 virsh destroy $1
1701 virsh undefine $1
1702 }
1703
1704
1705
1706 vspicy() { # usage: VIRSH_DOMAIN
1707 # connect to vms made with virt-install
1708 spicy -p $(sudo virsh dumpxml "$1"|grep "<graphics.*type='spice'"|\
1709 sed -r "s/.*port='([0-9]+).*/\1/")
1710 }
1711
1712
1713 wtr() { curl wttr.in/boston; }
1714
1715 xl() {
1716 if pgrep gnome-screensav &>/dev/null; then
1717 # this command actually starts gnome-screensaver if it isn't running.
1718 # lololol, what crap
1719 gnome-screensaver-command --exit &>/dev/null
1720 fi
1721 mate-screensaver-command --exit &>/dev/null
1722 if ! pidof xscreensaver; then
1723 pushd /
1724 xscreensaver &
1725 popd
1726 # 1 was not long enough
1727 sleep 3
1728 fi
1729 xscreensaver-command -activate
1730 }
1731
1732 #############################
1733 ######### misc stuff ########
1734 #############################
1735
1736 # from curl cheat.sh/:bash_completion
1737 _cheatsh_complete_curl()
1738 {
1739 local cur prev opts
1740 _get_comp_words_by_ref -n : cur
1741
1742 COMPREPLY=()
1743 #cur="${COMP_WORDS[COMP_CWORD]}"
1744 prev="${COMP_WORDS[COMP_CWORD-1]}"
1745 opts="$(curl -s cheat.sh/:list | sed s@^@cheat.sh/@)"
1746
1747 if [[ ${cur} == cheat.sh/* ]] ; then
1748 COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
1749 __ltrim_colon_completions "$cur"
1750 return 0
1751 fi
1752 }
1753 complete -F _cheatsh_complete_curl curl
1754
1755
1756 if [[ $- == *i* ]]; then
1757 # commands to run when bash exits normally
1758 trap "hl" EXIT
1759 fi
1760
1761
1762 # temporary variables to test colorization
1763 # some copied from gentoo /etc/bash/bashrc,
1764 use_color=false
1765 # dircolors --print-database uses its own built-in database
1766 # instead of using /etc/DIR_COLORS. Try to use the external file
1767 # first to take advantage of user additions.
1768 safe_term=${TERM//[^[:alnum:]]/?} # sanitize TERM
1769 match_lhs=""
1770 [[ -f ~/.dir_colors ]] && match_lhs="${match_lhs}$(<~/.dir_colors)"
1771 [[ -f /etc/DIR_COLORS ]] && match_lhs="${match_lhs}$(</etc/DIR_COLORS)"
1772 [[ -z ${match_lhs} ]] \
1773 && type -P dircolors >/dev/null \
1774 && match_lhs=$(dircolors --print-database)
1775 # test if our $TERM is in the TERM values in dircolor
1776 [[ $'\n'${match_lhs} == *$'\n'"TERM "${safe_term}* ]] && use_color=true
1777
1778
1779 if ${use_color} && [[ $- == *i* ]]; then
1780
1781 if [[ $XTERM_VERSION == Cygwin* ]]; then
1782 get_term_color() {
1783 for x in "$@"; do
1784 case $x in
1785 underl) echo -n $'\E[4m' ;;
1786 bold) echo -n $'\E[1m' ;;
1787 red) echo -n $'\E[31m' ;;
1788 green) echo -n $'\E[32m' ;;
1789 blue) echo -n $'\E[34m' ;;
1790 cyan) echo -n $'\E[36m' ;;
1791 yellow) echo -n $'\E[33m' ;;
1792 purple) echo -n $'\E[35m' ;;
1793 nocolor) echo -n $'\E(B\E[m' ;;
1794 esac
1795 done
1796 }
1797
1798 else
1799 get_term_color() {
1800 for x in "$@"; do
1801 case $x in
1802 underl) echo -n $(tput smul) ;;
1803 bold) echo -n $(tput bold) ;;
1804 red) echo -n $(tput setaf 1) ;;
1805 green) echo -n $(tput setaf 2) ;;
1806 blue) echo -n $(tput setaf 4) ;;
1807 cyan) echo -n $(tput setaf 6) ;;
1808 yellow) echo -n $(tput setaf 3) ;;
1809 purple) echo -n $(tput setaf 5) ;;
1810 nocolor) echo -n $(tput sgr0) ;; # no font attributes
1811 esac
1812 done
1813 }
1814 fi
1815 else
1816 get_term_color() {
1817 :
1818 }
1819 fi
1820 # Try to keep environment pollution down, EPA loves us.
1821 unset safe_term match_lhs use_color
1822
1823
1824
1825
1826
1827
1828 ###############
1829 # prompt ######
1830 ###############
1831
1832
1833 if [[ $- == *i* ]]; then
1834 # git branch/status prompt function
1835 if [[ $OS != Windows_NT ]]; then
1836 GIT_PS1_SHOWDIRTYSTATE=true
1837 fi
1838 # arch source lopip show -fcation
1839 [[ -r /usr/share/git/git-prompt.sh ]] && source /usr/share/git/git-prompt.sh
1840 # fedora/debian source
1841 [[ -r /usr/share/git-core/contrib/completion/git-prompt.sh ]] && source /usr/share/git-core/contrib/completion/git-prompt.sh
1842
1843 # in case we didn't source git-prompt.sh
1844 if ! declare -f __git_ps1 > /dev/null; then
1845 __git_ps1() {
1846 :
1847 }
1848 fi
1849
1850 # this needs to come before next ps1 stuff
1851 # this stuff needs bash 4, feb 2009,
1852 # old enough to no longer condition on $BASH_VERSION anymore
1853 shopt -s autocd
1854 shopt -s dirspell
1855 PS1='\w'
1856 if [[ $- == *i* ]] && [[ ! $RLC_INSIDE_EMACS ]]; then
1857 PROMPT_DIRTRIM=2
1858 bind -m vi-command B:shell-backward-word
1859 bind -m vi-command W:shell-forward-word
1860 fi
1861
1862 if [[ $SSH_CLIENT ]]; then
1863 PS1="\h $PS1"
1864 fi
1865
1866
1867
1868
1869 prompt-command() {
1870 local return=$? # this MUST COME FIRST
1871 local psc pst ps_char ps_color stale_subvol
1872 unset IFS
1873 history -a # save history
1874
1875
1876
1877 case $return in
1878 0) ps_color="$(get_term_color blue)"
1879 ps_char='\$'
1880 ;;
1881 1) ps_color="$(get_term_color green)"
1882 ps_char="$return \\$"
1883 ;;
1884 *) ps_color="$(get_term_color yellow)"
1885 ps_char="$return \\$"
1886 ;;
1887 esac
1888 if [[ ! -O . ]]; then # not owner
1889 if [[ -w . ]]; then # writable
1890 ps_color="$(get_term_color bold red)"
1891 else
1892 ps_color="$(get_term_color bold green)"
1893 fi
1894 fi
1895 # I would set nullglob, but bash has had bugs where that
1896 # doesn't work if not in top level.
1897 if [[ -e /nocow/btrfs-stale ]] && ((`ls -AUq /nocow/btrfs-stale|wc -l`)); then
1898 ps_char="! $ps_char"
1899 fi
1900 PS1="${PS1%"${PS1#*[wW]}"} \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1901 # emacs completion doesn't like the git prompt atm, so disabling it.
1902 #PS1="${PS1%"${PS1#*[wW]}"}$(__git_ps1 ' (%s)') \[$ps_color\]$ps_char\[$(get_term_color nocolor)\] "
1903 }
1904 PROMPT_COMMAND=prompt-command
1905
1906 settitle () {
1907 if [[ $TERM == screen* ]]; then
1908 local title_escape="\033]..2;"
1909 else
1910 local title_escape="\033]0;"
1911 fi
1912 if [[ $* != prompt-command ]]; then
1913 echo -ne "$title_escape$USER@$HOSTNAME ${PWD/#$HOME/~} $*\007"
1914 fi
1915 }
1916
1917 # for titlebar
1918 # condition from the screen man page i think
1919 if [[ $TERM == *(screen*|xterm*|rxvt*) ]]; then
1920 trap 'settitle "$BASH_COMMAND"' DEBUG
1921 else
1922 trap DEBUG
1923 fi
1924
1925 fi
1926
1927 reset-konsole() {
1928 # we also have a file in /a/c/...konsole...
1929 local f=$HOME/.config/konsolerc
1930 setini DefaultProfile profileian.profile "Desktop Entry" $f
1931 setini Favorites profileian.profile "Favorite Profiles" $f
1932 setini ShowMenuBarByDefault false KonsoleWindow $f
1933 setini TabBarPosition Top TabBar $f
1934 }
1935
1936 reset-sakura() {
1937 while read k v; do
1938 setini $k $v sakura /a/c/subdir_files/.config/sakura/sakura.conf
1939 done <<'EOF'
1940 colorset1_back rgb(33,37,39
1941 less_questions true
1942 audible_bell No
1943 visible_bell No
1944 disable_numbered_tabswitch true
1945 scroll_lines 10000000
1946 scrollbar true
1947 EOF
1948 }
1949
1950 reset-xscreensaver() {
1951 # except for spash, i set these by setting gui options in
1952 # xscreensaver-command -demo
1953 # then finding the corresponding option in .xscreensaver
1954 # spash, i happened to notice in .xscreensaver
1955 cat > /home/iank/.xscreensaver <<'EOF'
1956 mode: blank
1957 dpmsEnabled: True
1958 dpmsStandby: 0:01:00
1959 dpmsSuspend: 0:01:00
1960 dpmsOff: 0:02:00
1961 timeout: 0:01:00
1962 lock: True
1963 lockTimeout: 0:02:00
1964 splash: False
1965 EOF
1966
1967 }
1968
1969
1970 ###########################################
1971 # stuff that makes sense to be at the end #
1972 ###########################################
1973 if [[ "$SUDOD" ]]; then
1974 cd "$SUDOD"
1975 unset SUDOD
1976 elif [[ -d /a ]] && [[ $PWD == $HOME ]] && [[ $- == *i* ]]; then
1977 cd /a
1978 fi
1979
1980
1981 # best practice
1982 unset IFS
1983
1984
1985 # if someone exported $SOE, catch errors
1986 if [[ $SOE ]]; then
1987 errcatch
1988 fi
1989
1990 # I'd prefer to have system-wide, plus user ruby, due to bug in it
1991 # https://github.com/rubygems/rubygems/pull/1002
1992 # further problems: installing multi-user ruby and user ruby,
1993 # you don't get multi-user ruby when you sudo to root, unless its sudo -i.
1994 # There a third hybrid form, which passenger error suggested I use,
1995 # but it didn't actually work.
1996
1997 # in cased I never need this
1998 # rvm for non-interactive shell: modified from https://rvm.io/rvm/basics
1999 #if [[ $(type -t rvm) == file && ! $(type -t ruby) ]]; then
2000 # source $(rvm 1.9.3 do rvm env --path)
2001 #fi
2002
2003 # based on warning from rvmsudo
2004 export rvmsudo_secure_path=1
2005
2006 if [[ -s "/usr/local/rvm/scripts/rvm" ]]; then
2007 source "/usr/local/rvm/scripts/rvm"
2008 elif [[ -s $HOME/.rvm/scripts/rvm ]]; then
2009 source $HOME/.rvm/scripts/rvm
2010 fi
2011
2012 export GOPATH=$HOME/go
2013 path_add $GOPATH/bin
2014
2015 export ARDUINO_PATH=/a/opt/Arduino/build/linux/work
2016
2017 path_add --end ~/.npm-global
2018
2019
2020 # didn't get drush working, if I did, this seems like the
2021 # only good thing to include for it.
2022 # Include Drush completion.
2023 # if [ -f "/home/ian/.drush/drush.complete.sh" ] ; then
2024 # source /home/ian/.drush/drush.complete.sh
2025 # fi
2026
2027
2028 # https://wiki.archlinux.org/index.php/Xinitrc#Autostart_X_at_login
2029 # i added an extra condition as gentoo xorg guide says depending on
2030 # $DISPLAY is fragile.
2031 if [[ ! $DISPLAY && $XDG_VTNR == 1 ]] && shopt -q login_shell && isarch; then
2032 exec startx
2033 fi
2034
2035
2036 # ensure no bad programs appending to this file will have an affect
2037 return 0