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