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