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