# .bashrc
# cayla fauver <cayla@cay.la>
# Created: Sat Sep 17, 2005  07:55PM
# Last modified: Fri Aug 19, 2011 12:32PM
# Description:
# Written to work on both linux and Macs.  Things not working
# are commented.  Stolen from many place and tweaked to work for me.
# Feel free to take all or some if you like it.

##########################
# per workstation settings
source ~/.bashlocalrc   # settings that vary per workstation

if [ "$PS1" ]; then  # If running interactively...

    ##################
    # startup programs
    if [ "$USE_SCREEN" = "Y" ]; then
        if [ "$UID" -ne 0 ]; then
            if [ "$SHLVL" -eq 1 ]; then
                /usr/bin/screen -d -RR
            fi
        fi
    fi

    if [ -e "/usr/games/fortune" ]; then
        echo "Fortune: "
        /usr/games/fortune
        echo
    fi
    if [ -e "/usr/bin/uptime" ]; then
        echo "Uptime: ` /usr/bin/uptime`"
    fi
    echo
    
    # Make $HOME comfy
    if [ ! -d "${HOME}/bin" ]; then
        mkdir ${HOME}/bin
        chmod 700 ${HOME}/bin
        echo "${HOME}/bin was missing.  I created it for you."
    fi
    if [ ! -d "${HOME}/Documents" ]; then
        if ! [  -d "${HOME}/data" ]; then
            mkdir ${HOME}/data
            chmod 700 ${HOME}/data
            echo "${HOME}/data was missing.  I created it for you."
        fi
    fi
    if [ ! -d "${HOME}/tmp" ]; then
        mkdir ${HOME}/tmp
        chmod 700 ${HOME}/tmp
        echo "${HOME}/tmp was missing.  I created it for you."
    fi

    ~/bin/rc_sync.sh

    #######################################################################################
    #  color chart:
    #  Black       0;30     Dark Gray     1;30      Blue        0;34     Light Blue    1;34
    #  Red         0;31     Light Red     1;31      Purple      0;35     Light Purple  1;35
    #  Green       0;32     Light Green   1;32      Cyan        0;36     Light Cyan    1;36
    #  Brown       0;33     Yellow        1;33      Light Gray  0;37     White         1;37
    #  No color    0
    red='\e[0;31m'
    RED='\e[1;31m'
    blue='\e[0;34m'
    BLUE='\e[1;34m'
    cyan='\e[0;36m'
    CYAN='\e[1;36m'
    green='\e[0;32m'
    GREEN='\e[1;32m'
    yellow='\e[0;33m'
    YELLOW='\e[1;33m'
    NC='\e[0m'

    ###########################
    # prompt & window functions
    
    function reset_display()
    {
        if [ "$SHLVL" -eq 1 ]; then
            echo $DISPLAY > $HOME/.display
        else
            if [ -e $HOME/.display ]; then
                export DISPLAY=$(cat $HOME/.display)
            fi
        fi
    }

    function host_load()
    {
        THRESHOLD_LOAD=50
        COLOUR_LOW=$GREEN
        COLOUR_HIGH=$RED

        if [ $OS = "Linux" ]; then
            ONE=$(uptime | sed -e "s/.*load average: \(.*\...\),\(.*\...\),\(.*\...\)/\1/" -e "s/ //g")
        fi
        if [ $OS = "Darwin" ]; then
            ONE=$(uptime | sed -e "s/.*load averages: \(.*\...\)\(.*\...\)\(.*\...\)/\1/" -e "s/ //g")
        fi
        ONEHUNDRED=$(echo -e "scale=0 \n $ONE/0.01 \nquit \n" | bc)
        if [ $ONEHUNDRED -gt $THRESHOLD_LOAD ]
            then
                HOST_COLOR=$COLOUR_HIGH
            else
                HOST_COLOR=$COLOUR_LOW 
        fi
    }

    function set_xtitle()
    {
        if [[ $TERM == *term* ]]; then
            echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"
        fi
    }

    function short_pwd()
    {
        # How many characters of the $PWD should be kept
        local pwdmaxlen=25
        # Indicate that there has been dir truncation
        local trunc_symbol=".."
        local dir=${PWD##*/}
        pwdmaxlen=$(( ( pwdmaxlen < ${#dir} ) ? ${#dir} : pwdmaxlen ))
        NEW_PWD=${PWD/#$HOME/\~}
        local pwdoffset=$(( ${#NEW_PWD} - pwdmaxlen ))
        if [ ${pwdoffset} -gt "0" ]
        then
            NEW_PWD=${NEW_PWD:$pwdoffset:$pwdmaxlen}
            NEW_PWD=${trunc_symbol}/${NEW_PWD#*/}
        fi
    }

    function shrhist()
    {
        history -a $HISTFILE
        history -n $HISTFILE
    }

    function power_prompt()
    {
        host_load
        set_xtitle
        short_pwd
        shrhist
        if [ "$UID" -eq 0 ]; then
            PS1="[\[${HOST_COLOR}\]\t\[${NC}\]][\[${red}\]\u\[${NC}\]@\[${green}\]\H\[${NC}\]:\[${cyan}\]${NEW_PWD}\[${NC}\]]\\$ "
        else
            PS1="[\[${HOST_COLOR}\]\t\[${NC}\]][\[${yellow}\]\u\[${NC}\]@\[${green}\]\H\[${NC}\]:\[${cyan}\]${NEW_PWD}\[${NC}\]]\\$ "
        fi
    }  

    function lite_prompt()
    {
        set_xtitle
        short_pwd
        shrhist
        if [ "$UID" -eq 0 ]; then
            PS1="[\t][\[${red}\]\u\[${NC}\]@\[${green}\]\H\[${NC}\]:\[${cyan}\]${NEW_PWD}\[${NC}\]]\\$ "
        else
            PS1="[\t][\[${yellow}\]\u\[${NC}\]@\[${green}\]\H\[${NC}\]:\[${cyan}\]${NEW_PWD}\[${NC}\]]\\$ "
        fi
    }

    if [ $PROMPT = "power" ]; then
        PROMPT_COMMAND=power_prompt
    else 
        PROMPT_COMMAND=lite_prompt
    fi

    ##################
    # on exit function
    function _exit()
    {
        svn ci ~/rc/
        echo -e "${RED}So long and thanks for all the fish${NC}"
    }

    trap _exit EXIT

fi # End interactive bits

##############
# random stuff
OS=$(uname)             # for resolving pesky os differing switches
ulimit -S -c 0          # Don't want any coredumps
#umask 007
#stty stop undef
#stty start undef

###############
# bash settings
set -o notify                           # notify when jobs running in background terminate
set -o nounset                          # attempt to use undefined variable outputs error message and forces exit
#set -o xtrace                          # useful for debuging
#set -o ignoreeof                       # can't c-d out of shell
#set -o noclobber                       # prevents catting over file

shopt -s cdable_vars                    # if arg to cd is not a dir assume it is a variable
shopt -s cdspell                        # if arg to cd has a minor typo, fix it automatically
shopt -s checkhash                      # check commands in hash table for existness prior to running
shopt -s checkwinsize                   # update lines and columns if terminal resized
shopt -s cmdhist                        # save all of multiline cmds in history
shopt -s extglob                        # enable extended pattern matching
shopt -s histappend histreedit histverify   # append instead of overwrite, allow re-edit failed sub, verify command execution when pulling from history
shopt -s no_empty_cmd_completion        # no tab completion on otherwise empty lines
shopt -s sourcepath                     # look in the path for any files used as args to source/.
#shopt -u mailwarn                       # notify when mail has been read

###########
# variables
export EDITOR="vi"
export VISUAL="vi"
export HISTCONTROL=erasedups
export HISTSIZE=100000
export HISTTIMEFORMAT="%Y-%m-%d %T "
if [ -d $HOME/Maildir/ ]; then
    export MAIL=$HOME/Maildir/
    export MAILPATH=$HOME/Maildir/
    export MAILDIR=$HOME/Maildir/
elif [ -f /var/mail/$USER ]; then
    export MAIL="/var/mail/$USER"
fi
if [ "$TERM" = "screen" ]; then
    export TERM=$TERMINAL
fi 

if [ "$OS" = "Linux" ]; then
    source ~/.lscolorsrc
elif [ "$OS" = "Darwin" ]; then
    export LSCOLORS='gxfxcxdxbxegedabagacad'
fi

#########
# aliases
if [ "$OS" = "Linux" ]; then
    alias ls="ls --color=auto -h"
elif [ "$OS" = "Darwin" ]; then
    alias ls="ls -G"
fi
alias ..="cd .."
alias be="vi ~/.bashrc;source ~/.bashrc"
alias c="clear"
alias cp="cp -i"
alias df="df -h"
if [ "$OS" = "Darwin" ]; then
    alias gvim="/Applications/MacVim.app/Contents/MacOS/Vim -g"
fi
alias install="apt-get install"
alias la="ls -A"
alias ll="ls -lh"
alias lla="ls -lhA"
alias mkdir="mkdir -p"
alias mv="mv -i"
alias path="env | grep PATH"
alias ps="ps aux"
alias rcci="svn ci ~/rc/"
alias rcup="~/bin/rc_sync.sh"
alias rm="rm -i"
alias scpresume="rsync --partial --progress --rsh=ssh"
alias se="vi ~/.screenrc"
alias sr="screen -d -RR"
if [ -e "${HOME}/.homeIP.txt" ]; then
    alias sshh="ssh -p 322 cayla@`cat ~/.homeIP.txt`"
fi
alias svn-list-non="svn status --no-ignore | grep '^\?' | sed 's/^\?      //'"
alias svn-rm-non="svn status --no-ignore | grep '^\?' | sed 's/^\?      //'  | xargs -Ixx rm -rf xx"
alias upgrade="apt-get update;apt-get upgrade -y"
alias ve="vi ~/.vimrc"
alias vi="vim"
alias xmas="perl -MAcme::POE::Tree -e 'Acme::POE::Tree->new()->run()'"

######
# PATH
if [ "$UID" -eq 0 ]; then
    PATH=$PATH:/usr/local:/usr/local/sbin:/usr/sbin:/sbin
fi
PATH=$PATH:$HOME/bin
 
# remove duplicate path entries
export PATH=$(echo $PATH | awk -F: '
{ for (i = 1; i <= NF; i++) arr[$i]; }
END { for (i in arr) printf "%s:" , i; printf "\n"; } ')

##############
# ~/ functions
function private()
{
    find $HOME -type d -exec chmod 700 {} \;
    find $HOME -type f -exec chmod 600 {} \;
    find $HOME/bin -type f -exec chmod +x {} \;
    find $HOME/.dropbox-dist/dropbox* -type f -exec chmod +x {} \;
}

function public()
{
    if [ -d $HOME/public_html ]; then
        chown -R $USER:www-data $HOME/public_html
        chmod 755 $HOME/public_html
        find $HOME/public_html/ -type d -exec chmod 775 {} \;
        find $HOME/public_html/ -type f -exec chmod 664 {} \;
        chmod 755 $HOME
    fi
}

function setperms()
{
    echo "setting proper permissions in ~/"
    private
    public
}

function wwwrc()
{
    alias mv="mv"
    mv -f ~/.[a-z]*.html ~/public_html/
    chmod 644 ~/public_html/.[a-z]*.html
    chown cayla:www-data ~/public_html/.[a-z]*.html
    alias mv="mv -i"
}

####################################
# common commands piped through grep
function aptg()  # debian specific.
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
        echo "search debian package list"
        echo "usage: aptg [program/keyword]"
    else
        apt-cache search $1 | sort | less
    fi
}

function hg()
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then  
        echo "search bash history"
        echo "usage: hg [search pattern]"
    else                
        history | grep -i "$1" | grep -v hg
    fi      
}

function lsofg()
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
        echo "grep lsof"
        echo "usage: losfg [port/program/whatever]"
    else
        lsof | grep -i $1 | less
    fi
}

function psg()
{
    if [ $# -lt 1 ] || [ $# -gt 1 ]; then
        echo "grep running processes"
        echo "usage: psg [process]"
    else                
        ps aux | grep USER | grep -v grep
        ps aux | grep -i $1 | grep -v grep
    fi      
}

#########################
# random useful functions
function apath()
{
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo "Temporarily add to PATH"
        echo "usage: apath [dir]"
    else
        PATH=$1:$PATH
    fi
}

function ds()
{
    echo "size of directories in MB"
    if [ $# -lt 1 ] || [ $# -gt 2 ]; then
        echo "you did not specify a directy, using pwd"
        DIR=$(pwd)
        find $DIR -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    else
        find $1 -maxdepth 1 -type d -exec du -sm \{\} \; | sort -nr
    fi
}

function mergeinfo()
{
    re="http"
    logb="false"
    if [ $# -lt 1 ]; then
        echo "show the svn log for checkins eligible for merging"
        echo "usage: mergeinfo [source] [destination] {includelogging -l}"
    else 
        destination=$2
        if [[ $1 =~ $re ]]; then
            # command if URL is provided as source
            source=$1
        else
            source=$(svn info $1 | grep URL | awk '{ print $2 }')
            echo "converted working directory $1 into URL $source ..."
        fi
        if [ $# -gt 2 ]; then
            if [ "$3" = "-l" ]; then
                logb="true"
            fi
        fi
        if [ "$logb" = "true" ]; then
            svn mergeinfo $source --show-revs eligible $destination | sed -e 's:r\([0-9]*\):-r \1:' | xargs svn log $source
        else
            svn mergeinfo $source --show-revs eligible $destination
        fi 
    fi
}

# http://zzamboni.org/brt/2008/05/07/removing-all-extended-attributes-from-a-directory-tree/index.html
function rr()
{
    for i in $(ls -Rl@ | grep '^    ' | awk '{print $1}' | sort -u); \
       do echo Removing $i ... >&2;  \
       find . | xargs xattr -d $i 2>/dev/null ; done
}

function sshpg()
{
    if [ $# -lt 1 ]; then
        echo "create ssh tunnel for postgres"
        echo "usage: sshpg username@server [port]"
        echo "ssh -N \$1 -L \$2/localhost/5432"
    else
        ssh -N $1 -L $2/localhost/5432
    fi
}