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