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