#!/usr/bin/env zsh
#
# System variables
#

if [[ $defpath == ""  && -d ~/bin ]]
then
	defpath=($path)
	path=(
		$defpath
		~/bin
	)
	if [[ -d ~/.gem/ruby/*/bin ]]
	then
		path=(
			$path
			~/.gem/ruby/*/bin
		)
	fi
fi

if [[ ! -d ~/.zsh/cache ]]
then
	mkdir -p ~/.zsh/cache
fi

myfuncs=( ~alan/dotfiles/zsh/functions/*(/) )
fpath=(
	$myfuncs
	~alan/dotfiles/zsh/completion/
	$fpath
)

export PATH
export PAGER="less"
export EDITOR="emacsclient"
export CLICOLOR=true

#
# zsh variables
#
HISTFILE=~/.zsh/history
HISTSIZE=4000
SAVEHIST=3000

WORDCHARS='*?_-[]~=.&;!#$%^(){}<>'

#If a command takes more than 5 seconds, give statistics
REPORTTIME=5
TIMEFMT="%U user %S system %P cpu %*Es total"

#Check for user logins
watch=notme
WATCHFMT="%n has %a %l from %M at %t"

hosts=(
	server
	prefect
	alanpearce.co.uk
	home.alanpearce.co.uk
	lethalrocks.uk.to
	alphapulsar.uk.to
	st.alphapulsar.uk.to
	a.st.alphapulsar.uk.to
	st
)

users=(alan root toor)

function linkAuthSock () {
	local linkSock=~/.ssh/ssh_auth_sock
	ln -sf $1  ~/.ssh/ssh_auth_sock
	export SSH_AUTH_SOCK=$linkSock
}

if [[ "$SSH_AUTH_SOCK" != "" ]]
then
	if [[ -e ~/.ssh/ssh_auth_sock && ! -L ~/.ssh/ssh_auth_sock ]]
	then
		linkAuthSock $SSH_AUTH_SOCK
	fi
fi

case $OSTYPE in
	*gnu*)
		os=gnu
		;;
	freebsd*)
		os=freebsd
		;;
	darwin*)
		os=osx
esac

LS_COLORS='no=00:fi=00:di=36:ln=35:pi=30;44:so=35;44:do=35;44:bd=33;44:cd=37;44:or=05;37;41:mi=05;37;41:ex=01;31:*.cmd=01;31:*.exe=01;31:*.com=01;31:*.bat=01;31:*.reg=01;31:*.app=01;31:*.txt=32:*.org=32:*.md=32:*.mkd=32:*.h=32:*.c=32:*.C=32:*.cc=32:*.cpp=32:*.cxx=32:*.objc=32:*.sh=32:*.csh=32:*.zsh=32:*.el=32:*.vim=32:*.java=32:*.pl=32:*.pm=32:*.py=32:*.rb=32:*.hs=32:*.php=32:*.htm=32:*.html=32:*.shtml=32:*.erb=32:*.haml=32:*.xml=32:*.rdf=32:*.css=32:*.sass=32:*.scss=32:*.less=32:*.js=32:*.coffee=32:*.man=32:*.0=32:*.1=32:*.2=32:*.3=32:*.4=32:*.5=32:*.6=32:*.7=32:*.8=32:*.9=32:*.l=32:*.n=32:*.p=32:*.pod=32:*.tex=32:*.bmp=33:*.cgm=33:*.dl=33:*.dvi=33:*.emf=33:*.eps=33:*.gif=33:*.jpeg=33:*.jpg=33:*.JPG=33:*.mng=33:*.pbm=33:*.pcx=33:*.pdf=33:*.pgm=33:*.png=33:*.ppm=33:*.pps=33:*.ppsx=33:*.ps=33:*.svg=33:*.svgz=33:*.tga=33:*.tif=33:*.tiff=33:*.xbm=33:*.xcf=33:*.xpm=33:*.xwd=33:*.xwd=33:*.yuv=33:*.aac=33:*.au=33:*.flac=33:*.mid=33:*.midi=33:*.mka=33:*.mp3=33:*.mpa=33:*.mpeg=33:*.mpg=33:*.ogg=33:*.ra=33:*.wav=33:*.anx=33:*.asf=33:*.avi=33:*.axv=33:*.flc=33:*.fli=33:*.flv=33:*.gl=33:*.m2v=33:*.m4v=33:*.mkv=33:*.mov=33:*.mp4=33:*.mp4v=33:*.mpeg=33:*.mpg=33:*.nuv=33:*.ogm=33:*.ogv=33:*.ogx=33:*.qt=33:*.rm=33:*.rmvb=33:*.swf=33:*.vob=33:*.wmv=33:*.doc=31:*.docx=31:*.rtf=31:*.dot=31:*.dotx=31:*.xls=31:*.xlsx=31:*.ppt=31:*.pptx=31:*.fla=31:*.psd=31:*.7z=1;35:*.apk=1;35:*.arj=1;35:*.bin=1;35:*.bz=1;35:*.bz2=1;35:*.cab=1;35:*.deb=1;35:*.dmg=1;35:*.gem=1;35:*.gz=1;35:*.iso=1;35:*.jar=1;35:*.msi=1;35:*.rar=1;35:*.rpm=1;35:*.tar=1;35:*.tbz=1;35:*.tbz2=1;35:*.tgz=1;35:*.tx=1;35:*.war=1;35:*.xpi=1;35:*.xz=1;35:*.z=1;35:*.Z=1;35:*.zip=1;35:*.ANSI-30-black=30:*.ANSI-01;30-brblack=01;30:*.ANSI-31-red=31:*.ANSI-01;31-brred=01;31:*.ANSI-32-green=32:*.ANSI-01;32-brgreen=01;32:*.ANSI-33-yellow=33:*.ANSI-01;33-bryellow=01;33:*.ANSI-34-blue=34:*.ANSI-01;34-brblue=01;34:*.ANSI-35-magenta=35:*.ANSI-01;35-brmagenta=01;35:*.ANSI-36-cyan=36:*.ANSI-01;36-brcyan=01;36:*.ANSI-37-white=37:*.ANSI-01;37-brwhite=01;37:*.log=01;34:*~=01;34:*#=01;34:*.bak=01;36:*.BAK=01;36:*.old=01;36:*.OLD=01;36:*.org_archive=01;36:*.off=01;36:*.OFF=01;36:*.dist=01;36:*.DIST=01;36:*.orig=01;36:*.ORIG=01;36:*.swp=01;36:*.swo=01;36:*,v=01;36:*.gpg=34:*.gpg=34:*.pgp=34:*.asc=34:*.3des=34:*.aes=34:*.enc=34:'

#Ignore suffixes in completion
fignore=(
    svbin
)

#
# Modules
#
autoload -Uz compinit bashcompinit
autoload -U colors complist zrecompile zmv zargs zed
autoload -Uz vcs_info
autoload insert-files
zle -N insert-files
zmodload -i zsh/complist
colors
compinit -u -d .zsh/cache/compdump
bashcompinit

zstyle :compinstall filename '/home/alan/.zshrc'

autoload -Uz _tmux_pane_words
zle -C tmux-pane-words-prefix   complete-word _generic
zle -C tmux-pane-words-anywhere complete-word _generic
zstyle ':completion:tmux-pane-words-(prefix|anywhere):*' completer _tmux_pane_words
zstyle ':completion:tmux-pane-words-(prefix|anywhere):*' ignore-line current
zstyle ':completion:tmux-pane-words-anywhere:*' matcher-list 'b:=* m:{A-Za-z}={a-zA-Z}'

# Speed up completion by not going further than a full match
zstyle ':completion:*' accept-exact '*(N)'

zstyle ':completion:*:default' use-cache on
zstyle ':completion:*:default' cache-path ~/.zsh/cache/compcache

zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' '+m:{A-Z}={a-z}'
zstyle ':completion:*' completer _oldlist _expand _force_rehash _complete _match

zstyle ':completion:*'              verbose    yes
zstyle ':completion:*:messages'     format     '%d'
zstyle ':completion:*:warnings'     format     'No   matches  for: %d'
zstyle ':completion:*:descriptions' format     '%U%B%d%b%u'
zstyle ':completion:*:corrections'  format     '%B%d (errors: %e)%b'
zstyle ':completion:*'              group-name ''

# Complete all user processes
zstyle ':completion:*:processes' command 'ps -au$USER'
# Add colour to process lists
zstyle ':completion:*:*:kill:*:processes' list-colors '=(#b) #([0-9]#)*=0=01;31'
zstyle ':completion:*:*:kill:*'           menu        yes    select
zstyle ':completion:*:kill:*'             force-list  always
zstyle ':completion:*:*:killall:*'        menu        yes    select
zstyle ':completion:*:killall:*'          force-list  always

# Complete unreadable log filenames
#zstyle ':completion::complete:(most|tail)::' fake-files '/var/log/*:current'

# Group manpages by section
zstyle ':completion:*' separate-sections true

# Users
#zstyle '*' users $users

zstyle '*' hosts $hosts

zstyle ':completion:*:functions' ignored-patterns '_*'
zstyle ':completion:*:cd:*'	     ignore-parents parent pwd

#This works, but isn't the same as ls
#zstyle ':completion:*:default' list-colors ''
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}

zstyle ':vcs_info:*' enable git hg

# Filename suffixes to ignore during completion (except after rm command)
zstyle ':completion:*:*:(^rm):*:*files' ignored-patterns '*?.o' '*?.c~' '*?.old' '*?.pro'

## Prompt
if [[ $TERM != 'dumb' ]]
then
	autoload -U promptinit
	promptinit
	prompt pure
fi

# Options

# Changing directories
setopt auto_cd

# Completion
setopt auto_list # List multiple choices on first tab
unsetopt list_ambiguous # List ambiguous choices rather than completing common prefixes
unsetopt list_beep # Don't try to beep here
setopt list_types # Indicate file types

# Expansion and globbing
setopt extended_glob # Use #~^ as part of filename patterns
unsetopt nomatch

# History
unsetopt hist_beep
setopt hist_expire_dups_first
setopt hist_fcntl_lock # Use standard locking on histfile
setopt hist_find_no_dups
setopt hist_ignore_space
setopt hist_reduce_blanks
setopt hist_verify
setopt inc_append_history

# Input/Output
unsetopt clobber
unsetopt flow_control
setopt path_dirs # Search PATH even with slashes
setopt print_exit_value

# Job Control
setopt auto_continue
unsetopt nohup
setopt long_list_jobs
unsetopt notify

# Scripts and functions
unsetopt multi_func_def
setopt multios

# Zle
unsetopt beep

############
# Keybinds #
############
#KiTTY
bindkey "OD"    backward-word
bindkey "OC"    forward-word

#General
bindkey "[1~"   beginning-of-line
bindkey "[4~"   end-of-line
bindkey "[5~"   beginning-of-history
bindkey "[6~"   end-of-history
bindkey "[2~"   quoted-insert
bindkey "[3~"   delete-char

bindkey ''      backward-delete-char

bindkey '^I'      expand-or-complete-prefix
bindkey ''    reverse-menu-complete
bindkey ''    up-line-or-search
bindkey ''    down-line-or-search

#urxvt
bindkey '[3;5~' delete-word
bindkey '' backward-word
bindkey '' forward-word

bindkey 'f'	  insert-files
bindkey 'd'     describe-key-briefly

bindkey '\'	  tmux-pane-words-prefix
bindkey '|'	  tmux-pane-words-anywhere

# Aliases before functions
alias getcflags='gcc -\#\#\# -march=native -E /usr/include/stdlib.h 2>&1 | grep "/usr/libexec/gcc/.*cc1"'
alias grep='grep --color=auto'
alias df='df -h'
alias du='du -h'
alias md='mkdir -p'
alias rd='rmdir'
alias .='source'

ls='\ls'
gnu_ls_options="-v --group-directories-first --color=auto"
gnu_ls_isodate="--time-style=long-iso"
bsd_ls_options="-p"
bsd_ls_isodate="-D '%F %k:%M'"

case $os in
	osx)
		if [[ -n $commands[gls] ]]
		then
			ls='\gls'
			ls_options=$gnu_ls_options
			ls_isodate=$gnu_ls_isodate
		else
			ls_options=$bsd_ls_options
			ls_isodate=$bsd_ls_isodate
		fi
		;;
	freebsd)
		ls_options=$bsd_ls_options
		ls_isodate=$bsd_ls_isodate
		;;
	gnu)
		ls_options=$gnu_ls_options
		ls_isodate=$gnu_ls_isodate
		;;
esac
alias l="${ls} ${ls_options} -Bp"
alias l1="${ls} ${ls_options} -1"
alias ls="${ls} ${ls_options} -hF"
alias la="${ls} ${ls_options} -hA"
alias ll="${ls} ${ls_options} ${ls_isodate} -hl"
alias lal="ll -A"
alias lla="lal"
alias llr="ll -t"
alias gpp='g++'
alias lsr="${ls} -tld *(m-2)" # mtime < -2days

alias trans="transmission-remote transmission.home"
alias bitcoin="bitcoind"
alias su="smart_sudo "
alias e="$EDITOR"
alias E="SUDO_EDITOR=\emacsclient -c -a emacs\" sudoedit"
alias wprop='xprop |awk '\''
    /^WM_CLASS/{sub(/.* =/, "instance:"); sub(/,/, "\nclass:"); print}
    /^WM_NAME/{sub(/.* =/, "title:"); print}
    /^WM_WINDOW_ROLE/{sub(/.* =/, "role:"); print}'\'''

alias -g ...='../..'

#Suffix aliases
alias -s log=less

if [[ -e =hub ]]; then
	alias git="hub"
fi

# Functions

precmd () {
    [[ -t 1 ]] || return
    case $TERM in
		*xterm*|rxvt|putty|(dt|k|E)term|screen*) print -Pn "\e]2;%~\a"
		;;
	esac
}

pid () {
    local i
    for i in /proc/<->/stat
    [[ "$(< $i)" = *\((${(j:|:)~@})\)* ]] && echo $i:h:t
    return 0
}

_force_rehash() {
    (( CURRENT == 1 )) && rehash
    return 1        # Because we didn't really complete anything
}

portgrep() {
    sudo lsof -i :$1 -nP | egrep '(LISTEN|UDP|COMMAND)'
}

ipgrep() {
    sudo lsof -i @$1 -nP
}

smart_sudo () {
    if [[ -n $1 ]]; then
        \sudo $argv
    else
        #if no parameters were given, then assume we want a root shell
        \sudo -i -u toor
    fi
}

compdef _sudo smart_sudo

smart_compile () {
	local zcompargs
	if [[ $1 = *zshrc* ]]; then
		zcompargs="-R"
	fi

	if [[ $EUID -ne 0 || $1 != *alan* ]]; then
		zrecompile -q -p $zcompargs $1
	fi
	if [[ -n $2 ]]; then
		. $1
	fi
}

_FASD_DATA="$HOME/.zsh/fasd-data"
autoload -U fasd
source ~/.zsh/cache/fasd-init-zsh
alias e="f -e $EDITOR"