Update.
[scripts.git] / bashrc
1 # -*-Shell-script-*-
2
3 #########################################################################
4 # This program is free software: you can redistribute it and/or modify  #
5 # it under the terms of the version 3 of the GNU General Public License #
6 # as published by the Free Software Foundation.                         #
7 #                                                                       #
8 # This program is distributed in the hope that it will be useful, but   #
9 # WITHOUT ANY WARRANTY; without even the implied warranty of            #
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      #
11 # General Public License for more details.                              #
12 #                                                                       #
13 # You should have received a copy of the GNU General Public License     #
14 # along with this program. If not, see <http://www.gnu.org/licenses/>.  #
15 #                                                                       #
16 # Written by and Copyright (C) Francois Fleuret                         #
17 # Contact <francois@fleuret.org> for comments & bug reports             #
18 #########################################################################
19
20 # The site-specific and confidential settings are in another file
21
22 PRIVATE_BASHRC="${HOME}/private/bashrc.perso"
23
24 # If the MANPATH is not set, set it
25
26 [ "${MANPATH}" ] || MANPATH=$(manpath)
27
28 # If the private bashrc exists, execute it
29
30 [ -f "${PRIVATE_BASHRC}" ] && source "${PRIVATE_BASHRC}"
31
32 # !!! THIS HAS TO BE HERE EVEN IN THE NON-INTERACTIVE PART OR YOU WILL
33 # LOSE YOU PREVIOUS HISTORY !!!
34
35 export HISTFILESIZE=20000
36 export HISTSIZE=${HISTFILESIZE}
37
38 export HISTIGNORE="${HISTIGNORE}:&:[ ]*"
39
40 # I want to save the command time, but I do not want to see it in
41 # history
42
43 export HISTTIMEFORMAT=""
44
45 shopt -s histappend
46
47 # I realized that most of my settings are meaningful only in
48 # interactive mode. This should maybe be done more properly through
49 # using different .bash_profile and .bash_login
50
51 [[ ${TERM} == "dumb" ]] || [ ! -t 0 ] && return
52
53 # Remove the annoying beeps in console
54
55 setterm -blength 0
56
57 ######################################################################
58 ## The interactive part
59
60 export VT_RESET=$'\e[0m'
61 export VT_BOLD=$'\e[1m'
62 export VT_UNDERLINE=$'\e[4m'
63 export VT_BLINK=$'\e[5m'
64
65 export VT_SET_TITLE=$'\e]0;'
66 export VT_END_TITLE=$'\007'
67
68 export VT_BLACK_FG=$'\e[30m'
69 export VT_RED_FG=$'\e[31m'
70 export VT_GREEN_FG=$'\e[32m'
71 export VT_YELLOW_FG=$'\e[33m'
72 export VT_BLUE_FG=$'\e[34m'
73 export VT_MAGENTA_FG=$'\e[35m'
74 export VT_CYAN_FG=$'\e[36m'
75 export VT_WHITE_FG=$'\e[37m'
76
77 export VT_BLACK_BG=$'\e[40m'
78 export VT_RED_BG=$'\e[41m'
79 export VT_GREEN_BG=$'\e[42m'
80 export VT_YELLOW_BG=$'\e[43m'
81 export VT_BLUE_BG=$'\e[44m'
82 export VT_MAGENTA_BG=$'\e[45m'
83 export VT_CYAN_BG=$'\e[46m'
84 export VT_WHITE_BG=$'\e[47m'
85
86 # Colorize man pages!
87
88 export LESS_TERMCAP_us=${VT_GREEN_FG}
89 export LESS_TERMCAP_ue=${VT_RESET}
90 export LESS_TERMCAP_md=${VT_BLUE_FG}${VT_BOLD}
91 export LESS_TERMCAP_me=${VT_RESET}
92
93 # export LESS_TERMCAP_md=$'\e[1;34;40m'
94
95 # This prevents ^S from freezing the shell
96
97 # stty -ixon
98
99 ulimit -c unlimited
100
101 alias ..='cd ..'
102 alias -- -='cd -'
103 alias rm='rm -i'
104 alias mv='mv -i'
105 # alias chmod='chmod -v'
106 alias chmod='chmod -c'
107 alias cp='cp -i -v'
108 alias rd=rmdir
109 alias md='mkdir -pv'
110 alias ps='ps uxaf'
111 alias df='df -hT --sync'
112 alias grep='grep -i -E --color=auto'
113 alias find='ionice -c3 find'
114 alias pd=pushd
115 alias val='valgrind --leak-check=full --show-reachable=yes --db-attach=yes '
116
117 alias s='screen -d -R -U && clear'
118
119 function nh () {
120     export HISTFILE=/dev/null
121     unalias cd
122 }
123
124 function ding () {
125     if [[ $1 && $(which winshepherd.sh) ]]; then
126         play -q ~/local/sounds/deskbell.wav &
127         unset E_APP_WINDOW
128         winshepherd.sh message green "$1"
129     else
130         play -q ~/local/sounds/deskbell.wav
131     fi
132 }
133
134 # alias kj="keyjnote -s -D 1000 -t Crossfade -T 100"
135 alias impressive="impressive -s -D 1000 -t Crossfade -T 100"
136
137 # alias fdupes='fdupes -r .'
138
139 # ls colors
140
141 if [ -e "${HOME}/.dircolors" ]; then
142     eval $(dircolors "${HOME}/.dircolors")
143     alias ls='ls -p --group-directories-first --color'
144     alias lt='ls -p --color -gohtr --time-style="+%Y %b %d %H:%M"'
145     alias ll='ls -p --color -goh --time-style="+%Y %b %d %H:%M"'
146     alias lll='ls -p --color -lth'
147     alias l='ls -p --color -I "*~" -I "*.o"'
148     alias less='less -R'
149 else
150     alias ls='ls -p --group-directories-first'
151     alias lt='ls -p -gohtr --time-style="+%Y %b %d %H:%M"'
152     alias ll='ls -p -goh --time-style="+%Y %b %d %H:%M"'
153     alias lll='ls -p -lth'
154     alias l='ls -p -I "*~" -I "*.o"'
155 fi
156
157 export EDITOR=emacsclient
158 export GIT_EDITOR=${EDITOR}
159
160 ######################################################################
161 # Ignored extensions when completing
162
163 # export FIGNORE="CVS"
164
165 function latexdiff () {
166     # wdiff -n \
167     # -w $'\033[30;43m'"[$1]"$'\033[30;41m ' -x $'\033[0m' \
168     # -y $'\033[30;43m'"[$2]"$'\033[30;42m ' -z $'\033[0m' \
169     # $*
170
171     wdiff -n \
172         -w $'\033[30;41m' -x $'\033[0m' \
173         -y $'\033[30;42m' -z $'\033[0m' \
174         $*
175
176     # | \grep $'\033'"\|section{"
177 }
178
179 # Looks for the most recent .log and pdflatex + bibtex the
180 # corresponding tex file
181
182 function rl () {
183     RECENT_LOG=$(ls -t $(find -maxdepth 1 -name "*.log" -type f) | head -1)
184
185     if [[ ${RECENT_LOG} ]]; then
186         FILEBASE="${RECENT_LOG/.log/}"
187
188         if [[ -f "${FILEBASE}.tex" ]]; then
189
190             pdflatex "${FILEBASE}"
191             bibtex "${FILEBASE}"
192             pdflatex "${FILEBASE}"
193             pdflatex "${FILEBASE}"
194
195             if [[ "$1" ]]; then
196                 if [[ "$1" == "-v" ]] || [[ "$1" == "--view" ]]; then
197                     xpdf "${FILEBASE}.pdf"
198                 elif [[ "$1" == "-p" ]] || [[ "$1" == "--print" ]]; then
199                     lpr "${FILEBASE}.pdf"
200                 else
201                     echo "Usage: rl [-v|--view] [-p|--print]" >&2
202                     echo "Unknown option $1" >&2
203                     return 1
204                 fi
205             fi
206
207         else
208
209             echo "Can not find a tex file corresponding to the most recent log (${RECENT_LOG/.log/})." >&2
210             return 1
211
212         fi
213
214     else
215         echo "Can not find a recent log." >&2
216         return 1
217     fi
218 }
219
220
221 ######################################################################
222 # Functions
223
224 # Find a file whose name contains a substring
225
226 function fn () {
227     name=$1
228     shift
229     find "$@" -name "*${name}*";
230 }
231
232 function bak () {
233     while [[ "$1" ]]; do
234         cp "$1" "$1".bak
235         shift
236     done
237 }
238
239 function ua () {
240
241     [[ "$1" ]] || ( echo "Universal unarchive: ua <file> [<file> ...]" >&2 && return 1)
242
243     while [[ "$1" ]]; do
244
245         case "$1" in
246
247             *.tgz|*.tar.gz|*.tbz|*.tar.bz2)
248                 tar xvf "$1"
249                 ;;
250
251             *.rar)
252                 unrar -kb x "$1"
253                 ;;
254
255             *.zip)
256                 unzip "$1"
257                 ;;
258
259             *)
260                 echo "Unknown file extension $1"
261                 ;;
262         esac
263
264         shift
265
266     done
267 }
268
269 # Create a dir and cd there
270
271 function mcd () {
272     mkdir -vp "$1"
273     cd "$1"
274 }
275
276 # Capture the screen in a dated png
277
278 function cap () {
279     if [[ $2 ]]; then
280         name=$2
281     else
282         name="capture-$(date +%s).png"
283     fi
284     echo "Waiting $1 s and saving to ${name}."
285     [[ "$1" ]] && sleep "$1"
286     echo "Please click on the window to capture."
287     xwd  | convert - ${name}
288     \ls -l ${name}
289 }
290
291 # Create and CD in a /tmp/tmp.XXXXXX directory. With the '-'
292 # arguments, do not create one and CD in the most recent instead
293
294 function cdt () {
295     if [[ "$1" ]]; then
296         if [[ "$1" == "-" ]]; then
297             cd $(\ls -td /tmp/tmp.?????? | head -1)
298         else
299             echo "USAGE: cdt [-]" >&2
300             return 1
301         fi
302     else
303         dir=$(mktemp -d /tmp/tmp.XXXXXX)
304         link=/tmp/tmp
305         if [[ -h ${link} ]]; then
306             \rm ${link}
307         fi
308         if [[ ! -a ${link} ]]; then
309             ln -s ${dir} ${link}
310         fi
311         cd ${dir}
312     fi
313 }
314
315 alias t='cd /tmp'
316
317 function trash () {
318     TRASH=$(date +/tmp/trash-%Y-%b-%d-%Hh)
319     LINK=/tmp/trash
320
321     mkdir -p ${TRASH}
322
323     [[ -h ${LINK} ]] && \rm ${LINK}
324     [[ ! -f ${LINK} ]] && ln -s ${TRASH} ${LINK}
325
326     mv "$@" ${TRASH}
327     echo "Trashed $@"
328 }
329
330 function mmsget () {
331     mplayer "$1" -dumpstream -dumpfile $(basename "$1")
332 }
333
334 ######################################################################
335 # http://www.reddit.com/r/linux/comments/akt3j/a_functional_programming_style_map_function_for/
336
337 function map () {
338     local command i rep
339     if [ $# -lt 2 ] || [[ ! "$@" =~ :[[:space:]] ]];then
340         echo "Invalid syntax." >&2; return 1
341     fi
342     until [[ "$1" =~ : ]]; do
343         command="$command $1"; shift
344     done
345     command="$command ${1%:}"; shift
346     for i in "$@"; do
347         if [[ $command =~ \{\} ]];then
348             rep="${command//\{\}/\"$i\"}"
349             eval "${rep//\\/\\\\}"
350         else
351             eval "${command//\\/\\\\} \"${i//\\/\\\\}\""
352         fi
353     done
354 }
355
356 ######################################################################
357 ## A version of pho which stores the image numbers in environment
358 ## variables
359
360 function pho () {
361     TEMP=$(mktemp /tmp/pho.XXXXXXX)
362     $(which pho) "$@" | tee ${TEMP}
363     PHO_NOTE_1=$(grep ^"Note 1: " ${TEMP} | sed -e "s/^[^:]*: //")
364     PHO_NOTE_2=$(grep ^"Note 2: " ${TEMP} | sed -e "s/^[^:]*: //")
365     PHO_NOTE_3=$(grep ^"Note 3: " ${TEMP} | sed -e "s/^[^:]*: //")
366     PHO_NOTE_R90=$(grep ^"Rotate 90 \(CW\): " ${TEMP} | sed -e "s/^[^:]*: //")
367     PHO_NOTE_R180=$(grep ^"Rotate 180: " ${TEMP} | sed -e "s/^[^:]*: //")
368     PHO_NOTE_R270=$(grep ^"Rotate -90 \(CCW\): " ${TEMP} | sed -e "s/^[^:]*: //")
369     [[ "${PHO_NOTE_1}" ]] || unset PHO_NOTE_1
370     [[ "${PHO_NOTE_2}" ]] || unset PHO_NOTE_2
371     [[ "${PHO_NOTE_3}" ]] || unset PHO_NOTE_3
372     [[ "${PHO_NOTE_R90}" ]] || unset PHO_NOTE_R90
373     [[ "${PHO_NOTE_R180}" ]] || unset PHO_NOTE_R180
374     [[ "${PHO_NOTE_R270}" ]] || unset PHO_NOTE_R270
375     \rm ${TEMP}
376 }
377
378 ######################################################################
379 ## A version of date that shows the time at home if TZ is set
380
381 function dt () {
382     echo "Local: $(date)"
383     if [[ ${TZ} ]]; then
384         unset TZ
385         echo "Home:  $(date)"
386     fi
387 }
388
389 ######################################################################
390 ## ifup / ifdown with sudo and memorization of the network
391
392 ## When invoked without an argument netup uses the same argument as
393 ## the previous time
394
395 ## When invoked without an argument netdown removes the last interface
396 ## which was netuped
397
398 [[ ${NETUP_HISTORY} ]] || NETUP_HISTORY="${HOME}/.netup_history"
399
400 function netup () {
401     WIFI_INTERFACE=wlan0
402
403     if [[ $1 == "--scan" ]]; then
404         if [[ ! $(\ifconfig -s | grep ${WIFI_INTERFACE}) ]]; then
405             sudo ifconfig ${WIFI_INTERFACE} up
406             UPPED_WIFI=1
407         fi
408
409         sudo iwlist ${WIFI_INTERFACE} scan|grep ESS\|Quali\|Encry
410
411         if [[ ${UPPED_WIFI} ]]; then
412             sudo ifconfig ${WIFI_INTERFACE} down
413         fi
414
415         return 0
416     fi
417
418     if [[ $(\ifconfig -s | grep -v ^"(Iface|lo) ") ]]; then
419         echo "There is already interface(s) up." >&2
420         return 1
421     fi
422
423     if [[ $(\ps -C dhclient | tail -n +2) ]]; then
424         echo "There is already a dhcp client running." >&2
425         return 1
426     fi
427
428     if [[ $(\ps -C wpa_supplicant | tail -n +2) ]]; then
429         echo "There is already a wpa_supplicant running." >&2
430         return 1
431     fi
432
433     if [[ ! "$@" ]] && [[ -s ${NETUP_HISTORY} ]]; then
434         echo "netup <interface>" >&2
435         return 1
436         # # If we have no argument and there is a .netup_history, use it
437         # ARGS=$(cat ${NETUP_HISTORY})
438     else
439         # Otherwise uses the given arguments, and store them
440         ARGS="$@"
441         echo ${ARGS} > ${NETUP_HISTORY}
442     fi
443
444     if [[ -n "${PRIVATE_INTERFACE_DEFINITION}" ]]; then
445         ARGS="-i ${PRIVATE_INTERFACE_DEFINITION} ${ARGS}"
446     fi
447
448     echo "Executing ${VT_GREEN_FG}[sudo ifup ${ARGS}]${VT_RESET}"
449     sudo ifup ${ARGS}
450
451     # Ugly hack to remove the dsl modem dns server when we add
452     # explicitely a dns in the /etc/network/interfaces
453
454     REMOVE_LOCAL_DNS=/usr/local/bin/remove-local-dns.sh
455     # REMOVE_LOCAL_DNS=${HOME}/sources/scripts/remove-local-dns.sh
456
457     if [[ -x ${REMOVE_LOCAL_DNS} ]]; then
458         echo "Executing ${VT_GREEN_FG}[sudo ${REMOVE_LOCAL_DNS} 192.168]${VT_RESET}"
459         sudo ${REMOVE_LOCAL_DNS} 192.168
460     fi
461 }
462
463 function netdown () {
464     if [[ ! "$@" ]] && [[ -s ${NETUP_HISTORY} ]]; then
465         # If there are no arguments and there is a .netup_history, get the
466         # interface from it
467         ARGS=$(tail -1 ${NETUP_HISTORY} | sed -e "s/=.*$//")
468     else
469         # Otherwise, use the standard ifdown
470         ARGS="$@"
471     fi
472
473     if [[ -n "${PRIVATE_INTERFACE_DEFINITION}" ]]; then
474         ARGS="-i ${PRIVATE_INTERFACE_DEFINITION} ${ARGS}"
475     fi
476
477     echo "Executing sudo ${VT_GREEN_FG}[ifdown ${ARGS}]${VT_RESET}"
478     sudo ifdown ${ARGS}
479
480     # if [[ $(\ps -C dhclient | tail -n +2) ]]; then
481     # echo "There is still a dhcp client running." >&2
482     # return 1
483     # fi
484
485     # if [[ $(\ps -C wpa_supplicant | tail -n +2) ]]; then
486     # echo "There is still a wpa_supplicant running." >&2
487     # return 1
488     # fi
489 }
490
491 function checkgw () {
492     GW=$(route -n | grep ^0.0.0.0 | awk '{print $2}')
493     if [[ -n "${GW}" ]]; then
494         ping ${GW}
495     else
496         echo "Can not find a getaway." >&2
497         return 1
498     fi
499 }
500
501 ######################################################################
502 # Show the most recent files, no scroll
503
504 function lr () {
505     HEIGHT=$(stty size | awk '{print $1}')
506     WIDTH=$(stty size | awk '{print $2}')
507     \ls -goth --time-style="+%Y %b %d %H:%M" "$@" | \
508         head -$((HEIGHT-2)) | \
509         cut -b1-${WIDTH}
510 }
511
512 ######################################################################
513 # cd and ls into a directory
514 # [from http://www.oreillynet.com/onlamp/blog/2007/01/whats_in_your_bash_history.html]
515
516 function c () { cd "$@" && lr; }
517
518 ######################################################################
519 # You can change the xterm background color on the fly!
520
521 function setxtermbg () {
522     echo -n $'\e]11;'$1$'\007'
523 }
524
525 ######################################################################
526 # Shuffle the lines from the stdin
527
528 function shuffle () {
529     SEED=$1
530     [[ $SEED ]] || SEED=0
531     awk 'BEGIN{srand('${SEED}')} { print rand()" "$0 }' | sort -g | sed -e "s/^[0-9\.e\-]* //"
532 }
533
534 ######################################################################
535 # Stores the last entered command into a file
536
537 KEPT_COMMANDS=${HOME}/.kept_bash_commands
538
539 function keep () {
540     if [[ ${KEPT_COMMANDS} ]]; then
541         LINE="$*"
542         [[ "${LINE}" ]] || LINE=$(history | tail -2 | head -1 | sed -e "s/^[0-9 ]*//")
543         echo $LINE
544         echo $(date)": "${LINE} >> ${KEPT_COMMANDS}
545     else
546         echo "You have to set \$KEPT_COMMANDS"
547     fi
548 }
549
550 ######################################################################
551 # I sometime burn CDs and DVDs
552
553 function burn () {
554     DEVICE="/dev/cdrw"
555     if [[ ! "$1" ]]; then
556         echo "burn <iso name | dirname>" >&2
557     elif [[ -f "$1" ]]; then
558         if [[ $(file "$1" | grep "ISO 9660") ]]; then
559             wodim -eject -v dev=${DEVICE} "$1"
560         else
561             echo "Unknown type of $1" >&2
562         fi
563     elif [[ -d "$1" ]]; then
564         [[ "${TMP_ROOT}" ]] || TMP_ROOT=/tmp/
565         echo "Using ${TMP_ROOT} as temporary directory."
566         TMP=$(mktemp ${TMP_ROOT}/cdimage.XXXXXX) && \
567             genisoimage -input-charset iso8859-1 -r -o ${TMP} "$1" && \
568             wodim -eject -v dev=${DEVICE} ${TMP}
569         rm -f ${TMP}
570     else
571         echo "Can not find $1" >&2
572     fi
573 }
574
575 ######################################################################
576 # And watch DVDs too!
577
578 function dvd () {
579
580     echo
581     echo " ! @   Seek to the beginning of the previous/next chapter"
582     echo " j     Cycle through the available subtitles"
583     echo " o     Show/hide the timing"
584     echo " x z   Subtitle delay"
585     echo " / *   Volume"
586     echo
587
588     if [[ "$1" ]]; then
589         dvd_device="$1"
590         shift
591     else
592         dvd_device="/dev/dvd"
593     fi
594
595     title="1"
596
597     if [[ "$1" ]]; then
598         title=$1
599         shift
600     fi
601
602     # -vc ffmpeg12 -vf yadif
603
604     mplayer > /dev/null \
605         -stop-xscreensaver \
606         -quiet \
607         -alang en -slang en \
608         -softvol -softvol-max 1000 \
609         -dvd-device ${dvd_device} $* dvd://${title}
610 }
611
612 function ripdvd () {
613     if [[ -e "/dev/dvd" ]]; then
614         DVD_DEVICE="/dev/dvd"
615     elif [[ -e "/dev/dvd3" ]]; then
616         DVD_DEVICE="/dev/dvd3"
617     else
618         echo "Can not find the dvd device." >&2
619         return 1
620     fi
621
622     echo "Attemptin to rip from ${DVD_DEVICE}."
623
624     mkdir -p ${HOME}/dvds
625
626     cd ${HOME}/dvds
627     time dvdbackup -i ${DVD_DEVICE} -v -M $* && eject
628 }
629
630 alias ripcd=abcde
631
632 ######################################################################
633 # Upload the sources from the current directory to work
634
635 function ulsrc () {
636     if [[ ! "${MY_WORK_MACHINE}" ]]; then
637         echo "\$MY_WORK_MACHINE undefined" 1>&2
638         return 1
639     fi
640
641     DIR=${PWD/$HOME\//}
642
643     scp {Makefile,*.{cc,h,sh}} ${MY_WORK_MACHINE}:${DIR}
644
645     echo "Uploaded to ${MY_WORK_MACHINE}:${DIR}/"
646 }
647
648 ######################################################################
649 # Create small images from images
650
651 function mksmall () {
652
653     PARAMS="-geometry 800x600"
654
655     # Auto-orient does not seem to work at all, hence the ugly hack
656     # with exif below
657
658     # PARAMS="-auto-orient -geometry 800x600"
659
660     echo "Using ${PARAMS}"
661
662     DEST_DIR=$1
663
664     [[ ${DEST_DIR} ]] || DEST_DIR=./small
665
666     mkdir -p ${DEST_DIR}
667
668     if [[ ! -d ${DEST_DIR} ]]; then
669         echo "Can not create ${DEST_DIR}" >&2
670         return
671     fi
672
673     NB_TOTAL=$(find -maxdepth 1 -type f | wc -l)
674     NB=0
675
676     for i in $(find -maxdepth 1 -type f); do
677         if [[ $(file $i | grep image) ]]; then
678             if [[ -e ${DEST_DIR}/$i ]]; then
679                 echo "The file ${DEST_DIR}/$i already exists."
680             else
681
682                 # orientation=$(exif $i \
683                 # | grep ^Orientation \
684                 # | head -1 \
685                 # | sed -e "s/^[^|]*|//" \
686                 # | sed -e "s/ *$//")
687
688                 # case ${orientation} in
689                 # ""|"top - left")
690                 # rotation_cmd=""
691                 # ;;
692
693                 # "right - top")
694                 # rotation_cmd="-rotate 90"
695                 # ;;
696
697                 # "left - bottom")
698                 # rotation_cmd="-rotate 270"
699                 # ;;
700
701                 # *)
702                 # rotation_cmd=""
703                 # echo "Unknown orientation \"${orientation}\" !"
704                 # ;;
705                 # esac
706
707                 if [[ $(file ${i/%.*/}.* | grep -E movie) ]] ; then
708                     CAPTION_PARAMS="-font FreeSans-Bold -pointsize 32 -fill green -annotate +10+32 Video"
709                 else
710                     CAPTION_PARAMS=""
711                 fi
712
713                 convert ${rotation_cmd} $i ${PARAMS} ${CAPTION_PARAMS} ${DEST_DIR}/$i
714             fi
715
716             \ls -lt ${DEST_DIR}/$i
717         fi
718
719         NB=$((NB+1))
720
721         echo "$((NB*100/NB_TOTAL))% (${NB}/${NB_TOTAL})"
722     done
723 }
724
725 ######################################################################
726 # Move a file to the ~/sources/config directory and replace it where
727 # it was by a symbolic link
728
729 function mvtoconfig () {
730     CONFIGDIR=${HOME}/sources/config
731     if [[ -d ${CONFIGDIR} ]]; then
732         NEWNAME=${CONFIGDIR}/$(basename "$1" | sed -e "s/^\.//")
733         mv "$1" $NEWNAME
734         ln -s $NEWNAME $1
735     else
736         echo "Can not find ${CONFIGDIR}"
737     fi
738 }
739
740 ######################################################################
741 # Track uncommited files (I presume this is very ugly from a real git
742 # user perspective)
743
744 function git-fm () {
745     CURRENT_DIR=$(pwd)
746     NB_SUBDIR=0
747
748     for i in $(find -name ".git"); do
749         NB_SUBDIR=$((NB_SUBDIR+1))
750         cd ${CURRENT_DIR}/$(dirname $i)
751         NB_MODIFIED=$(git status | grep modified | wc -l)
752         if [[ ${NB_MODIFIED} -gt 0 ]]; then
753             echo "$(dirname $i) (${NB_MODIFIED})"
754             git status | grep modified \
755                 | sed -e "s/^#\t/    /" | sed -e "s/modified: *//"
756         fi
757     done
758
759     cd ${CURRENT_DIR}
760
761     echo "Visited ${NB_SUBDIR} directories."
762 }
763
764 function vcup () {
765     if [[ "$1" ]]; then
766         CURRENT=${PWD}
767         while [[ "$1" ]]; do
768             cd ${CURRENT}
769             cd $1
770             if [[ -d ".git" ]]; then
771                 echo "${PWD} is under GIT"
772                 git pull
773             elif [[ -d ".svn" ]]; then
774                 echo "${PWD} is under SVN"
775                 svn update
776             else
777                 echo "No known versioning system."
778             fi
779             shift
780         done
781         cd ${CURRENT}
782     else
783         vcup .
784     fi
785 }
786
787 ######################################################################
788 # Downloads torrents located in ${BT_DIR}/torrents/ and puts the
789 # result in the ${BT_DIR}
790
791 function bt () {
792     if [[ ${BT_DIR} ]]; then
793         if [[ -d "${BT_DIR}/torrents" ]]; then
794             if [[ "$1" ]]; then
795                 mv "$1" ${BT_DIR}/torrents
796             fi
797             if [[ "$(ps auxwww | grep btlaunchmanycurses | grep -v grep)" ]]; then
798                 echo "A client is already running."
799             else
800                 cd ${BT_DIR} && screen btlaunchmanycurses torrents --max_upload_rate 32
801             fi
802         else
803             echo "Directory ${BT_DIR}/torrents does not exist."
804         fi
805     else
806         echo "You have to set \$BT_DIR."
807     fi
808 }
809
810 ######################################################################
811 # The complex prompt policy
812
813 export PS1
814
815 if [ "${CONSOLE}" == "yes" ]; then
816     PS1=""
817 else
818
819     # If the login is a standard one (as specified in
820     # IGNORED_PROMPT_LOGIN, which is set in the private bash file), do not
821     # show it. I have IGNORED_PROMPT_LOGIN="^fleuret$".
822
823     if [ ! ${IGNORED_PROMPT_LOGIN} ] || [[ ! ${USER} =~ ${IGNORED_PROMPT_LOGIN} ]]; then
824         IDENT="${USER}"
825     fi
826
827     # If the display is not the main one, make the assumption that the
828     # shell is not running on the localhost, and show the hostname
829
830     [ "${DISPLAY}" != ":0.0" ] && IDENT="${IDENT}@\h"
831
832     # If there is the login or the hostname, add a ":" to the prompt
833
834     [ "${IDENT}" ] && IDENT="${IDENT}:"
835
836     # If we are root, show that in red
837
838     if [[ ${USER} == "root" ]]; then
839         PS1="\[${VT_RED_BG}${VT_WHITE_FG}\]${IDENT}\w\[${VT_RESET}\] "
840     else
841         PS1="\[${VT_WHITE_BG}${VT_BLACK_FG}\]${IDENT}\w\[${VT_RESET}\] "
842     fi
843
844     # In an xterm, show the hostname and path in the title bar, highlight
845     # the prompt
846
847     # [ "${TERMS_WITH_BAR}" ] || TERMS_WITH_BAR="^xterm|screen$"
848
849     # if [[ "${TERM}" =~ "${TERMS_WITH_BAR}" ]]; then
850     # PS1="\[${VT_SET_TITLE}shell@\h (\w)${VT_END_TITLE}${VT_WHITE_BG}\]${IDENT}\w\[${VT_RESET}\] "
851     # else
852     # PS1="\[${VT_WHITE_BG}\]${IDENT}\w\[${VT_RESET}\] "
853     # fi
854
855 fi
856
857 ######################################################################
858 # This implements a local history. If we are in a directory containing
859 # a writable local history file, we add the last line of the global
860 # history to it.
861
862 LOCAL_HISTORY_FILE=".local_bash_history"
863
864 function keep_local_history () {
865     if [[ -w "${LOCAL_HISTORY_FILE}" ]]; then
866         history 1 | sed -e 's/^ *[0-9]* *//' >> ${LOCAL_HISTORY_FILE}
867         TMP=$(mktemp /tmp/lh.XXXXXX)
868         \chmod 600 ${TMP}
869         uniq < ${LOCAL_HISTORY_FILE} | tail -${HISTSIZE} > ${TMP}
870         # mv would replace a symbolic link, while cp keeps it
871         \cp ${TMP} ${LOCAL_HISTORY_FILE}
872         \rm ${TMP}
873         LOCAL_HISTORY_HINT="* "
874     else
875         LOCAL_HISTORY_HINT=""
876     fi
877 }
878
879 PS1="\[${VT_WHITE_BG}\]\${LOCAL_HISTORY_HINT}\[${VT_RESET}\]${PS1}"
880
881 ######################################################################
882 # Switch off the history
883
884 function histfile_cue () {
885     if [[ ! "${HISTFILE}" == "${HOME}/.bash_history" ]]; then
886         HISTORY_CUE="[${HISTFILE}]"
887     else
888         HISTORY_CUE=""
889     fi
890 }
891
892 PS1="\[${VT_YELLOW_BG}\]\${HISTORY_CUE}\[${VT_RESET}\]${PS1}"
893
894 ######################################################################
895 # The dus command is available on my web site
896 #
897 # git clone http://fleuret.org/git/dus/
898
899 alias dus='dus -f -i'
900
901 ######################################################################
902 # The finddup command is available on my web site
903 #
904 # git clone http://fleuret.org/git/finddup/
905
906 alias finddup='finddup -p'
907
908 ######################################################################
909 # The selector command is available on my web site
910 #
911 # git clone http://fleuret.org/git/selector/
912
913 source bash-selector.sh --hist --cd
914
915 ######################################################################
916 # And we avoid to put in the history the use of the selector, which we
917 # do too often
918
919 HISTIGNORE="${HISTIGNORE}:selector-history"
920
921 ######################################################################
922
923 function selector-printer () {
924     TMP=$(mktemp /tmp/selector-printer.XXXXXX)
925     selector -o ${TMP} <(lpstat -a | awk '{print $1}')
926     export PRINTER=$(cat ${TMP})
927     echo "PRINTER=${PRINTER}"
928     rm -f ${TMP}
929     lpq
930 }
931
932 ######################################################################
933 # A ls with memory to notice what files have been added/removed from
934 # the current directory
935
936 function lsn () {
937     LSN_MEMORY=".lsn-state"
938     if  [[ $1 == "--mem" ]] || [[ "$1" == "-m" ]]; then
939         \ls -pa | sort > ${LSN_MEMORY}
940         echo "State updated." >&2
941     elif [[ -n "$1" ]]; then
942         echo "lsn [--mem|-m]" >&2
943         return 1
944     else
945         if [[ -f ${LSN_MEMORY} ]]; then
946             comm -1 -3 ${LSN_MEMORY} <(\ls -pa | sort)
947             comm -2 -3 ${LSN_MEMORY} <(\ls -pa | sort) | while read line; do
948                 echo "${VT_RED_FG}${VT_BOLD}${line}${VT_RESET} (missing)"
949             done
950         else
951             echo "No lsn state here." >&2
952             return 1
953         fi
954     fi
955 }
956
957 ######################################################################
958
959 function prompt_command () {
960     # save the history after every command to avoid loosing some when
961     # multiple shells are open
962     history -a
963     # load the saved history
964     history -n
965     # and the local histories system defined above
966     keep_local_history
967     # and the history cue
968     histfile_cue
969 }
970
971 PROMPT_COMMAND="prompt_command"
972
973 ######################################################################
974
975 # Displaying the timezone if it is set
976
977 if [[ ${TZ} ]]; then
978     echo "${VT_BOLD}${VT_GREEN_FG}Time zone is ${TZ}.${VT_RESET}"
979 fi
980
981 ######################################################################