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