## .zshrc
#cayla fauver <cayla@cay.la>
#Created: Sat Aug 20, 2011 01:16AM
#Last modified: Sat Feb 11, 2012 09:20PM
#Description:  based on http://pastebin.com/8ingysGL

source ~/.zshlocalrc                # settings that vary per workstation
source ~/.lscolorsrc
fpath=(~/rc/zsh/functions $fpath)   # custom plugins/functions
for ZSH_PLUGIN in ~/rc/zsh/plugins/*.zsh
do 
    source $ZSH_PLUGIN
done

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
    if [ ! -d "${HOME}/.ssh/tmp" ]; then
        mkdir -p ${HOME}/.ssh/tmp
        chmod 700 ${HOME}/.ssh/tmp
        echo "${HOME}/.ssh/tmp was missing.  I created it for you."
    fi
    
    # grab latest rc on launch
    cd ~/bin && git pull && cd -
    cd ~/rc && git pull && cd -

    case $TERM in
        *xterm*|ansi)
            #function settab { print -Pn "\e]1;%n@%m: %~\a" }
            function settitle { print -Pn "\e]2;%n@%m: %~\a" }
            #function chpwd { settab;settitle }
            #settab;settitle
            function chpwd { settitle }
            settitle
            ;;
    esac

    ##################
    # on exit function
    function _exit()
    {
        cd ~/bin/ ; git add . ; git commit -a ; git pull ; git push
        cd ~/rc/ ; git add . ; git commit -a ; git pull ; git push
        echo -e "${RED}So long and thanks for all the fish${NC}"
    }

    trap _exit EXIT

fi # End interactive bits

# autoloads
autoload colors; colors
autoload -U compinit
autoload -U zutil
autoload -U edit-command-line
zle -N edit-command-line
autoload -U promptinit
setopt prompt_subst
promptinit
prompt rainbows

compinit  # longest wait

# env settings
export EDITOR="vim"
export PAGER="less"
#export LANG="en_US.UTF8"
#export LC_ALL="en_US.UTF8"
export GREP_OPTIONS='--color=auto'
export GREP_COLOR='1;32'

# make ctrl-w work on path components
local WORDCHARS=${WORDCHARS//\//}

# number of lines kept in history
export HISTSIZE=10000
# number of lines saved in the history after logout
export SAVEHIST=10000
# location of history
export HISTFILE=~/.zhistory
# append command to history file once executed
setopt inc_append_history
# for sharing history between zsh processes
setopt SHARE_HISTORY
# Ignore duplicates in history
setopt HIST_IGNORE_ALL_DUPS
# Prevent record in history entry if preceding them with at least one space
setopt hist_ignore_space

# Nobody needs flow control anymore. Troublesome feature.
setopt noflowcontrol

# auto directory pushd that you can get dirs list by cd -[tab]
setopt auto_pushd

# Work without cd
setopt AUTOCD

# Regular expressions in files
setopt EXTENDEDGLOB

#allow tab completion in the middle of a word
setopt COMPLETE_IN_WORD

# Resume jobs after typing it's name
setopt AUTO_RESUME

# Dont quit console if processes are running
setopt CHECK_JOBS

# {{{ Completion
# :completion:<func>:<completer>:<command>:<argument>:<tag>
# Expansion options
zstyle ':completion:*' completer _complete _prefix _expand _approximate
zstyle ':completion::prefix-1:*' completer _complete
zstyle ':completion:incremental:*' completer _complete _correct
zstyle ':completion:predict:*' completer _complete
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}

# Separate matches into groups
zstyle ':completion:*:matches'  group 'yes'
zstyle ':completion:*'          group-name ''
zstyle ':completion:*:messages' format '%d'

# Messages/warnings format
zstyle ':completion:*:messages' format '%B%U---- %d%u%b'
# set format for warnings
zstyle ':completion:*:warnings' format $'%{\e[0;31m%}No matches for:%{\e[0m%} %d'
 
# Describe options in full
zstyle ':completion:*:options' description 'yes'
zstyle ':completion:*:options' auto-description '%d'

# colorful listings
zmodload -i zsh/complist
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*' special-dirs true
# activate color-completion(!)
#zstyle ':completion:*:default'         list-colors ${(s.:.)LS_COLORS}

# Nicer completion
zstyle ':completion:*:descriptions' format '%U%B%d%b%u'
zstyle ':completion:*:warnings' format '%BSorry, no matches for: %d%b'

# tab completion for PID
zstyle ':completion:*:*:kill:*' menu yes select
zstyle ':completion:*:kill:*' force-list always
zstyle ':completion:*:*:killall:*' menu yes select
zstyle ':completion:*:killall:*' force-list always

# on processes completion complete all user processes
zstyle ':completion:*:processes'       command 'ps -au$USER'

# cache
zstyle ':completion:*' use-cache 1
zstyle ':completion:*' cache-path ~/.zsh/cache
zstyle ':completion:*' accept-exact '*(N)'

# format on completion
zstyle ':completion:*:descriptions'    format $'%{\e[0;31m%}completing %B%d%b%{\e[0m%}'

# insert all expansions for expand completer
zstyle ':completion:*:expand:*'        tag-order all-expansions
zstyle ':completion:*:history-words'   list false
# activate menu
zstyle ':completion:*:history-words'   menu yes
# ignore duplicate entries
zstyle ':completion:*:history-words'   remove-all-dups yes
zstyle ':completion:*:history-words'   stop yes

# match uppercase from lowercase
zstyle ':completion:*'                 matcher-list 'm:{a-z}={A-Z}'
# offer indexes before parameters in subscripts
zstyle ':completion:*:*:-subscript-:*' tag-order indexes parameters
# provide verbose completion information
zstyle ':completion:*'                 verbose true
# define files to ignore for zcompile
zstyle ':completion:*:*:zcompile:*'    ignored-patterns '(*~|*.zwc)'
zstyle ':completion:correct:'          prompt 'correct to: %e'
# Ignore completion functions for commands you don't have:
zstyle ':completion::(^approximate*):*:functions' ignored-patterns '_*'

zstyle ':completion:*:complete:-command-::commands' ignored-patterns '*\~'

# arrow driven menu
zstyle ':completion:*' menu select

# define colors for less to get colored manpages
# or wget nion.modprobe.de/mostlike.txt && mkdir ~/.terminfo && cp mostlike.txt ~/.terminfo && tic ~/.terminfo/mostlike.txt
export LESS_TERMCAP_mb=$'\E[0;34m'  # begin blinking
export LESS_TERMCAP_md=$'\E[0;34m'  # begin bold
export LESS_TERMCAP_us=$'\E[01;34m' # begin underline
export LESS_TERMCAP_me=$'\E[0m'     # end mode
export LESS_TERMCAP_se=$'\E[0m'     # end standout-mode
export LESS_TERMCAP_so=$'\E[01;47;34m' # begin standout-mode - info box
export LESS_TERMCAP_ue=$'\E[0m'     # end underline
export GROFF_NO_SGR=1

# Key Bindings
bindkey '\C-x\C-e' edit-command-line    # ctrl-x,ctrl-e
bindkey "^[[3~" delete-char             # del
bindkey "\033[3~" delete-char           # del (macs only?)
bindkey "\e[1~" beginning-of-line       # home
bindkey "\033[H" beginning-of-line      # home (macs only?)
bindkey "\e[4~" end-of-line             # end
bindkey "\033[F" end-of-line            # end (macs only?)
bindkey "\e[5~" beginning-of-history    # page up
bindkey "\e[6~" end-of-history          # page down
bindkey "^R"    history-incremental-pattern-search-backward # ctrl + r
bindkey "^S"    history-incremental-pattern-search-forward  # ctrl + s
bindkey "^[[A"  up-line-or-history      # Up Arrow
bindkey "^[[B"  down-line-or-history    # Down Arrow
bindkey "\e\e[D" backward-word          # alt + left arrow
bindkey "\e\e[C" forward-word           # alt + right arrow
bindkey "^H"    backward-kill-word      # ctrl + backspace
bindkey "^[[3^" kill-word               # ctrl + delete

# Misc
OS=$(uname)             # for resolving pesky os differing switches

# 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"; } ')

# Aliases
if [ "$OS" = "Linux" ]; then
    alias ls="ls --color=auto -h"
elif [ "$OS" = "Darwin" ]; then
    alias ls="ls -G"
fi
alias ..="cd .."
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 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()'"
alias ze="vi ~/.zshrc;source ~/.zshrc"

# Functions

function git_fetch_cayla() {
    git clone ssh://cayla@cay.la:322/~/git/$1 ~/$1
}

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() {
    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 1 | 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 | grep USER | grep -v grep
        ps | grep -v grep | grep -i $1
    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 edit_commit() {
     if [ $# -lt 1 ] || [ $# -gt 3 ]; then
        echo "if you are in a WC, takes a single argument of rev #"
    else
        svn propedit -r $1 --revprop svn:log $2
    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 -n 2 svn log -g $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
}