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