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