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