# sniff out the platform
uname=`uname -s`
function linux() { [[ "$uname" = "Linux"  ]] }
function mac()   { [[ "$uname" = "Darwin" ]] }


# 1. Environment Vars
# ===================

[ -d /usr/local/riak ] && export RIAK=/usr/local/riak
[ -d ~/Projects/cappuccino/Build ] && export CAPP_BUILD=~/Projects/cappuccino/Build
[ -d ~/Projects/ssa/SSA-ios/Applications/SSA ] && export SSA=~/Projects/ssa/SSA-ios/Applications/SSA
[ -d ~/Projects/Xcode-build ] && export XCODE_BUILD=~/Projects/Xcode-build
if which narwhal-jsc >/dev/null 2>&1; then
    export NARWHAL_ENGINE=jsc
fi

if mac; then
    # for riak and possibly building javascriptcore
    export COMMAND_MODE=unix2003

    # Don't pollute tar archives with ._ files (Apple double files)
    export COPYFILE_DISABLE=true
fi

cdpath=(~)

HOSTNAME=`hostname -s`
KEYCHAIN_HOST=`hostname`

if [[ "x$INSIDE_EMACS" != "x" ]] || [[ "$EMACS" = "t" ]]; then
    export PAGER=cat
    export MANPAGER=cat
else
    export PAGER='less'
    # most rocks
    if which most >/dev/null 2>&1; then
            export MANPAGER='most'
    fi
fi

# default editors
if mac; then
    # wtf, you must be kidding, doesn't even work in many cases. really fucking lame!
    function emacsclient() {
        /Users/sjs/Applications/Emacs.app/Contents/MacOS/bin/emacsclient -s $(find /var/folders -name server -type s -uid $(id -u) 2>| /dev/null | grep emacs) $*
    }
    export EDITOR="vim"
    if which mate >/dev/null 2>&1; then
        export VISUAL="mate -w"
    else
        export VISUAL="vim"
    fi
elif linux && which emacs >/dev/null 2>&1; then
    export EDITOR="emacs -nw"
    export VISUAL="emacs"
else
    export EDITOR=vi
    export VISUAL=vi
fi


# 2. Limits
# =========
# limit coredumpsize        30m          # limit core dumps to 30mb
# limit stacksize            8m          # limit stack to 8mb

# 3. Shell Options
# ================

# 3.1. Parameters and Shell Functionality
# ---------------------------------------
#setopt ignoreeof           # ignore EOF ('^D') (i.e. don't log out on it)
setopt braceccl             # {a-d} expands to a b c d
setopt noclobber            # don't overwrite existing files w/ > output redir
setopt hist_allow_clobber   # C-p or UP and command has >| now, ready to go

# 3.2. Changing Directories
# -------------------------
setopt autocd               # automatically cd to a directory if not cmd
setopt autopushd            # automatically pushd directories on dirstack
setopt nopushdsilent        # print dirstack after each cd/pushd
setopt pushdignoredups      # don't push dups on stack

# need to find out the difference between these two, just the export?
setopt autonamedirs             # % export h=/home/sjs; cd ~h; pwd
                                # => /home/sjs
setopt cdablevars               # blah=~/media/movies; cd blah; pwd => ~/media/movies

# 3.3. Shell Completion
# ---------------------
setopt correct              # try to correct spelling...
setopt no_correctall        # ...only for commands, not filenames
setopt no_listbeep          # don't beep on ambiguous listings
setopt listpacked           # variable col widths (takes up less space)


# 3.4. Shell Expansion and Globbing
# ---------------------------------
setopt extendedglob         # use extended globbing (#, ~, ^)


# 3.5. History and History Expansion
# ----------------------------------
export HISTFILE="$ZDOTDIR/zhistory"    # save history
export HISTSIZE=200000                 # huge internal buffer
export SAVEHIST=200000                 # huge history file

setopt extendedhistory      # save timestamps in history
setopt no_histbeep          # don't beep for erroneous history expansions
setopt histignoredups       # ignore consecutive dups in history
setopt histfindnodups       # backwards search produces diff result each time
setopt histreduceblanks     # compact consecutive white space chars (cool)
setopt histnostore          # don't store history related functions
setopt incappendhistory     # incrementally add items to HISTFILE
# this is very annoying
#setopt histverify           # confirm !: or ^ command results before execution


# 3.6. Job Control
# ----------------
setopt longlistjobs         # list jobs in long format


# 3.7. Shell Prompt
# -----------------
setopt promptsubst          # allow paramater, command, so on in prompt
setopt transient_rprompt    # hide RPROMPT after cmdline is executed


# 3.8. ZLE
# --------
setopt no_beep          # don't beep on errors (in ZLE)

# when completing and then typing | > etc. don't delete
# the preceding space
self-insert-redir() {
    integer l=$#LBUFFER
    zle self-insert
    (( $l >= $#LBUFFER )) && LBUFFER[-1]=" $LBUFFER[-1]"
}
zle -N self-insert-redir
for op in \| \< \> \&
  do bindkey "$op" self-insert-redir
done



# 4. Terminal Settings 
# ====================

function precmd {
    rehash
}

autoload -U colors            # we need the colors for some formats below
colors


# 5. ZLE Keybindings
# ==================
bindkey '\ep' history-beginning-search-backward


# 6. Prompt Subsystem
# ===================

# Load the prompt theme system
autoload -U promptinit
promptinit
 
# Use my prompt theme, based on wunjo (zsh-git)
prompt sjs



# 7. Aliases
# ===========

# 7.1. Convenience Aliases/Macros
# --------------------------------
#alias burn='cdrecord -dao -driveropts=burnfree -dev=ATA:1,1,0 -v'
alias bgd='bg; disown %1'
alias cp='nocorrect cp'            # don't correct spelling for 'cp'
#alias dispatch-conf='sudo dispatch-conf'
alias ec="$EDITOR ~/config/"
alias ev="$EDITOR ~/config/vim/vimrc"
alias ez="$EDITOR $ZDOTDIR/zshrc && source $ZDOTDIR/zshrc"
alias rz="source $ZDOTDIR/zshrc"

if mac; then
    alias hide='sudo /Developer/Tools/SetFile -a VP'
fi

alias mkdir='nocorrect mkdir'      # don't correct spelling for 'mkdir'
alias mv='nocorrect mv'            # don't correct spelling for 'mv'
#alias ns='newscript'
#alias perldoc='LC_ALL=en_US perldoc'
#alias reboot='sudo shutdown -r now'
#alias shutdown='sudo shutdown -h now'
#alias ssh='ssh -X'
alias u='cd ..'
alias uu='cd ../..'
alias uuu='cd ../../..'
alias uuuu='cd ../../../..'

if mac; then
    alias chrome='/Users/sjs/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --allow-file-access-from-files >/dev/null 2>&1 &!'
fi

# ls Aliases 
# ----------------
if mac; then
    gls_path=`which gls`
    if [[ -x "$gls_path" ]]; then
        alias ls='$gls_path -BF --color=auto'
        alias la='$gls_path -AF --color=auto'
    else
        alias ls='ls -BF'
        alias la='ls -AF'
    fi
else
    alias ls='ls -BF --color=auto'
    alias la='ls -AF --color=auto'
fi
alias ll='ls -l'
alias lsd='ls -d'
alias lld='ls -dl'

# ruby
alias irb='irb --readline -r irb/completion'
alias rii='ri -Tf ansi'

# git
alias a='git add'
alias ap='git add -p'
alias b='git branch'
alias bt='git branch --track'
alias bto='git-branch-track-origin'
alias c='git commit'
alias co='git checkout'
alias cob='git checkout -b'
alias chp='git cherry-pick'
alias d='git diff'
alias dc='git diff --cached'
alias ds='git diff --stat'
alias f='hub fetch'
alias g='git grep'
alias gl='git log'
alias glo='git log --oneline --decorate'
alias gls='git log --stat'
alias gpr='git pull --rebase'
alias m='hub merge'
alias pob='git-pull-origin-branches'
alias r='hub remote'
alias ra='hub remote add'
alias rbi='git rebase -i'
GIT_VERSION="$(git --version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+')"
GIT_VERSION_MAJOR="${GIT_VERSION%%.*}"
GIT_VERSION_MINOR="${${GIT_VERSION%.*}#*.}"
GIT_VERSION_REVISION="${GIT_VERSION##*.}"
if [ $GIT_VERSION_MINOR -ge 7 ] && [ $GIT_VERSION_REVISION -ge 1 ]; then
    alias s='git status -sb'
else
    alias s='git status'
fi

git-branch-track-origin() { git branch --track "$1" origin/"$1" }

git-pull-origin-branches() {
    if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
	echo "$pwd is not part of a git repo"
	return
    fi
    origbranch=$(git branch | fgrep '*' | sed -e 's/\* //')
    branches=($@)
    [[ -z "$branches" ]] && branches=($(git branch | sed -e 's/\* //'))
    remote_branches=($(git branch -r | fgrep 'origin/' | fgrep -v HEAD | sed -e 's/\* //' -e 's#origin/##'))
    for branch ($branches) {
	[[ -z "${remote_branches[(r)$branch]}" ]] && continue
	git checkout $branch
	git pull origin $branch
    }
    git checkout $origbranch
}

# macports apachectl
if mac; then
    alias -g apache2ctl=/opt/local/apache2/bin/apachectl
fi

function e() {
    "$EDITOR" "$@" >/dev/null &!
}
alias et="$EDITOR . >/dev/null &!"
alias em='emacsclient'

# global aliases - work anywhere on line
alias -g C='|wc'
alias -g CL='|wc -l'
alias -g L='|$PAGER'
alias -g H='|head'
alias -g T='|tail'
alias -g G='|grep'
alias -g SH='>/dev/null 2>&1'
alias -g BGD='& disown %1'


# suffix aliases, 'alias -s ps=gv' makes '*.ps' expand to 'gv *.ps'
# (globbing done after alias expansion!)
#alias -s c=gvim
#alias -s h=gvim
#alias -s py=gvim
#alias -s html=gvim
#alias -s css=gvim

function cd () {
  if [[ -f $1 ]]; then
    builtin cd $1:h
  else
    builtin cd $1
  fi
}

function cl () {
  cd $1
  ls
}


function like(){
  print -l **/*${1}*{,/**}
}


# 8. Unsorted (new) stuff
# =======================

# if commands takes more than 60 seconds tell me how long it took
export REPORTTIME=60

# use less instead of the default more when no cmd is specified
export READNULLCMD=less

# set shell options
setopt no_badpattern            # supress err msgs
setopt cbases                   # 0xFF instead of 16#FF
setopt globsubst                # parameter expns eligible for filename expn & generation
setopt interactivecomments      # comments allowed in interactive shells
setopt no_hup                   # leave bg tasks running (a la nohup)
#setopt magicequalsubst         # performs filename expansion on 'arg' part of
                                #  foo=arg parameters.

bindkey -e                      # emacs style key bindings
bindkey '^I' complete-word      # complete on tab, leave expansion to _expand

# default in linux is backspace sends ^H, emacs no likey
#stty erase '^?'
TERMINFO=$HOME/.terminfo

function keep {
    setopt localoptions nomarkdirs nonomatch nocshnullglob nullglob
    kept=()         # Erase old value in case of error on next line
    kept=($~*)
    if [[ ! -t 0 ]]; then
        local line
        while read line; do
            kept+=( $line )         # += is a zsh 4.2+ feature
        done
    fi
print -Rc - ${^kept%/}(T)
}
alias keep='noglob keep '

# if [ -r "$HOME/.ruby/lib/sjs.rb" ]; then
#   export RUBYLIB="$HOME/.ruby/lib"
#   export RUBYOPT="rsjs"
# fi


# curl convenience functions
# ==========================
curl=`which curl`
if [[ -x "$curl" ]]; then
    function get {
        $curl -i -H 'x-requested-with: XMLHttpRequest' "$1"
    }

    function put {
        $curl -i -X PUT -H 'x-requested-with: XMLHttpRequest' -H 'content-type: application/json' -d "$2" "$1"
    }

    function post {
        $curl -i -X POST -H 'x-requested-with: XMLHttpRequest' -H 'content-type: application/json' -d "$2" "$1"
    }

    function delete {
        $curl -i -X DELETE -H 'x-requested-with: XMLHttpRequest' "$1"
    }
fi

# 9. Completion
# =============

# more verbose completion prompt
zstyle ':completion:*' format '%SCompleting %U%d%u%s'
zstyle :completion::complete:cd:: tag-order \
        local-directories path-directories

# The following lines were added by compinstall

zstyle ':completion:*' auto-description 'specify %d:'
zstyle ':completion:*' completer _expand _complete _files
zstyle ':completion:*' expand prefix
#zstyle ':completion:*' format 'Complete %d:'
zstyle ':completion:*' group-name ''
#zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*' list-prompt %SAt %p: Hit TAB for more, or the character to insert%s
zstyle ':completion:*' list-suffixes true
zstyle ':completion:*' matcher-list 'r:|[._-]=* r:|=*' 'r:|[._-]=* r:|=*' 'r:|[._-]=* r:|=*' 'r:|[._-]=* r:|=*'
#zstyle ':completion:*' max-errors 2
zstyle ':completion:*' menu select=0
zstyle ':completion:*' select-prompt %SScrolling active: current selection at %p%s
zstyle ':completion:*' verbose true
zstyle :compinstall filename "$ZDOTDIR/zshrc"

autoload -Uz compinit
compinit
# End of lines added by compinstall


# 10. SSH Keychain
# ================
# OS X includes keychain now, cool.
if which keychain >/dev/null 2>&1; then
    keychain ~/.ssh/id_rsa ~/.ssh/id_rsa-dreamhost
    source ~/.keychain/${KEYCHAIN_HOST}-sh > /dev/null
fi
