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