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