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