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