# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples

# Must come before shfuncs.sh, because we have a better quote()
if [[ $PS1 && -f /etc/bash_completion && -z "$BASH_COMPLETION" ]]; then
    . /etc/bash_completion
fi

. ~/bin/shfuncs.sh

# XXX remove me after next login
if ! [[ $PATH = *rakudobrew* ]]; then
    PATH=$HOME/.rakudobrew/bin:$PATH
fi

if (( BASH_VERSINFO[0] >= 4 )); then
    shopt -s globstar
fi


if type lesspipe >/dev/null 2>&1; then
    eval `lesspipe`
elif type lessfile >/dev/null 2>&1; then
    eval `lessfile`
fi

# My .inputrc binds C-w to kill-region (as in emacs), but that doesn't work
# if it is already set as the werase character.
tty -s && stty werase ^- 2>/dev/null

# Alias-like functions
vimgrep() {
    local pattern=$1
    shift;
    # When vim says "any non-ID character" it really means it.  We'll
    # assume that our RE won't have any ctrl-A characters.
    local delim=$'\001'
    vim -c "vimgrep $delim$pattern$delim $*"
}

tag() { vim -t "$*" -c 'norm z.'; }
ev() ( evince "$@" >/dev/null 2>&1 & )
ifeh() ( feh --force-aliasing -Z -g 512x512+2560+464 "${@}" >/dev/null 2>&1 & )

_gtl()  { git rev-parse --show-toplevel "$@"; }

gco()  { git checkout "${1-master}" ${1+"${@:2}"}; }
gg()   { gitg "${1-master}" ${1+"${@:2}"} >/dev/null 2>&1 & }
gfo()  { local br=${1-master}; shift; git fetch origin "$br:$br" "$@"; }
gf()   { local rep=${1-origin}; shift; git fetch "$rep" "$@"; }
gp()   { git pull "$@"; }
gu()   { git push "$@"; }
gb()   { git blame "$@"; }
gbr()  { git branch "$@"; }
gd()   { git diff "$@"; }
gdc()  { git diff --cached "$@"; }
gdt()  { git difftool "$@"; }
gmt()  { git mergetool "$@"; }
gde()  { git describe "$@"; }
gst()  { git status "$@"; }
gsl()  { git shortlog -sn "$@"; }
gl()   { git log "$@"; }
gls()  { git log --format="%h %s" "$@"; }
glr()  { git log --reverse "$@"; }
gll()  { git log -p --stat --reverse "$@"; }
gs()   { git show "$@"; }
gau()  { git add -u "$@"; }
gc()   { git commit "$@"; }
gca()  { git commit --amend "$@"; }
gcad() { git commit --amend --date="$(date)" "$@"; }
gcA()  { git commit --all "$@"; }
gcp()  { git cherry-pick -x "$@"; }
ga()   { git add "$@"; }
gam()  { git am "$@"; }
gfp()  { git format-patch "$@"; }
gai()  { git add -i "$@"; }
gri()  { git rebase -i "$@"; }
grc()  { git rebase --continue "$@"; }
gre()  { git rebase "$@"; }
grA()  { git rebase --abort "$@"; }
GB()   { (cd "$(_gtl)" && git bisect "$@"); }
GR()   { git reset "$@"; }
GRH()  { git reset --hard "$@"; }

gpr() {
    local pr=$1
    local desc=$2
    local branch=origin/pull/$pr/head
    local msg="Merge pull request #$pr from pull/$pr/head"
    if [[ $desc ]]; then
        msg="$msg"$'\n\n'"$desc"
    fi
    git merge --no-ff "$branch" -m "$msg"
}

gn() {
    local curr=$(git branch | sed -ne 's/^* //p')
    local branch=$curr
    if [[ "$1" && "$1" != -* ]]; then
        branch=$1
        shift
    fi
    local oldhead=$(git rev-list -n 1 --abbrev-commit "$branch")

    if [[ "$branch" = "$curr" ]]; then
        git pull
    else
        git fetch origin "$branch":"$branch"
    fi || return
   
    local newhead=$(git rev-list -n 1 --abbrev-commit "$branch")

    if [[ "$oldhead" != "$newhead" ]]; then 
        gll "$oldhead".."$branch" "$@"
        echo ">> That was: $oldhead..$branch"
    fi
}

# TODO: it would be nice to try to guess among diff, cpp, and maybe more;
# but since this is supposed to be used as a filter, that is nontrivial.
hlf() { highlight -O xterm256 -s moria -S "${1-diff}"; }

# Test whether a [ ] predicate is true in this directory or in
# any ancestor directory at least three directories deep in the
# hierarchy.  This last restriction is intended to avoid checking
# the user's ~/.git unless the user is in ~/ .
upwards() (
    # subshell!
    while ! test "$@"; do
        cd ..;
        [[ "$PWD" = */*/*/* ]] || exit 1 # exit the subshell
    done
    true
)

show_git_branch() {
    { git branch | sed -ne 's/$/]/ ; s/^* / [/p'; } 2>/dev/null
}

# If running interactively, then:
if [ "$PS1" ]; then
    if pid_is_terminal "$PPID"; then
        SHLVL=1
    fi

    # Use 256 colors in gnome-terminal (for xterm we use .Xresources).
    if [[ ($COLORTERM = gnome-* || $(ps -o command -p "$PPID") = *gnome-term*)
            && $TERM = xterm ]] && infocmp gnome-256color >/dev/null 2>&1
    then
        TERM=gnome-256color
    fi

    # If our terminal type is unknown on this machine, use xterm.
    if ! infocmp >/dev/null 2>&1; then
        TERM=xterm
    fi

    # If xterm is monochrome, use xterm-color if that exists.
    if [[ $TERM = xterm && $(tput colors) -lt 8 ]] && infocmp xterm-color >/dev/null 2>&1; then
        TERM=xterm-color
    fi

    eval "$(dircolors -b)"

    # Avoid classification characters in pipes, and avoid an
    # OpenSolaris b118 bug whereby /usr/bin/ls --color=auto
    # reports an error whenever it would not activate color.
    ls() {
        local carg="";
        [ -t 1 ] && carg="--color -F"
        command ls $carg "$@"
    }

    # If we have colors, set a fancy prompt.
    if [[ $TERM && $(tput colors) -ge 8 ]]; then
        dscolor=3
        [[ $(hostname) = dirac* ]] && dscolor=3
        [[ $(hostname) = church* ]] && dscolor=1
        [[ $(hostname) = trillian* ]] && dscolor=4
        PS1="$(printf "%$((SHLVL - 1))s" )"
        PS1+='\[$(dir_access_color)\]\w'
        PS1+='\['"$(tput sgr0)"'\]'
        PS1+='$(show_git_branch)'
        PS1+='\['"$(tput setaf $dscolor)$(tput bold)"'\]\$'
        PS1+='\['"$(tput sgr0)"'\] '
        # unexport PS1 so that non-bash shells don't get confused
        export -n PS1

        # make less colorful
        export LESS_TERMCAP_mb="$(tput bold; tput setaf 6)"
        export LESS_TERMCAP_md="$(tput bold; tput setaf 1)"
        export LESS_TERMCAP_me="$(tput sgr0)"
        export LESS_TERMCAP_se="$(tput sgr0)"
        export LESS_TERMCAP_so="$(tput bold; tput setaf 3; tput setab 4)"
        export LESS_TERMCAP_ue="$(tput sgr0)"
        export LESS_TERMCAP_us="$(tput bold; tput setaf 2)"
    fi


    # If this is an xterm set the title to user@host:dir
    case "$TERM" in
    xterm*|gnome*)
        PROMPT_COMMAND='nfm_xterm_title'
        ;;
    *)
        ;;
    esac


    shopt -s histappend
    unset HISTFILESIZE
    # export in case we need to do bash --norc
    export HISTSIZE=500000
    export HISTTIMEFORMAT="[%F %T] "

    shopt -s histreedit
    export TIMEFORMAT=$'%3U s.user + %3S s.sys  %3R s.elapsed  %P%%\n'
    #export MAILPATH='/var/mail/neil?You have mail.:/home/neil/mail/debian?You have debian mail.'
    export MAILPATH=/var/mail/neil
    export MAILCHECK=10
fi # interactive only


export JAVA_OPTS=-Djava.net.preferIPv4Stack=true
export VISUAL=vim
export EDITOR=vim
export PAGER=less
export GIT_PAGER="VIM_PAGER_MODE=1 view -"
export IRCNAME='Neil Moore <neil@s-z.org>'
export EMAIL=neil@s-z.org
export IRCNICK='\amethyst'
export IRCSERVER=irc.freenode.net # irc.vrfx.com
export SSFE='-beep'
export MAILREADER=/home/neil/bin/vmmail
export WWW_HOME='http://www.google.com/'
export PS_FORMAT='user,pid,stat,tname,bsdtime,pcpu,rss,sz,pmem,command'
export BC_ENV_ARGS="-l ${HOME}/.bcrc"
export ICAROOT="/home/neil/bin/CitrixICA"
export GCC_COLORS="locus=01;33"

unset PERL5LIB
if [[ $PERL5LIB != */Perl/lib/perl/* ]]; then
    _PERL_VERSION=$(perl --version | sed -ne 's/This is .*(v\([^)]*\)).*/\1/p')
    PERL5LIB="$HOME/Perl:$HOME/Perl/lib/perl/$_PERL_VERSION:$HOME/Perl/share/perl/$_PERL_VERSION${PERL5LIB:+:$PERL5LIB}"
    export PERL5LIB
fi