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