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