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