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