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