ZSH=$HOME/.ohmyzsh
DOTCONFDIR=$HOME/.dotconfigs

URL_OMZSH="https://github.com/robbyrussell/oh-my-zsh.git"

### Install oh-my-zsh

if [[ ! -d $ZSH ]]; then
    if curl --output /dev/null --silent -m 1  --head --fail "$URL_OMZSH"; then
	      echo "Installing Oh My ZSH"
	      git clone "$URL_OMZSH" $ZSH
    fi
fi


### Configure oh-my-zsh

# ZSH_THEME="pygmalion"

plugins=(
    git
    pip
    docker-compose
    python
    virtualenvwrapper
)

source $ZSH/oh-my-zsh.sh


### Configure zsh

# Configure prompt

prompt_segment() {
    [[ -n $1 ]] && color=$1 || return
    [[ -n $2 ]] && text='%{$fg['$color']%}'$2'%{$reset_color%}' || return
    [[ -n $3 ]] && sep='%{$fg[red]%}'$3'%{$reset_color%}' || sep=''
    echo -n $sep$text
}

prompt_git() {
    (( $+commands[git] )) || return
    if $(git rev-parse --is-inside-work-tree >/dev/null 2>&1); then
        ZSH_THEME_GIT_PROMPT_PREFIX="%{$reset_color%}%{$fg[green]%}"
        ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}"
        ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[yellow]%}⚡%{$reset_color%}"
        ZSH_THEME_GIT_PROMPT_CLEAN=""
        echo -n "git:$(git_prompt_info)"
    fi
}

prompt_virtualenv() {
  local virtualenv_path="$VIRTUAL_ENV"
  if [[ -n $virtualenv_path ]]; then
      text="penv:`basename $virtualenv_path`"
      echo -n $text 
  fi
}

prompt_condaenv() {
  local env_path="$CONDA_PREFIX"
  if [[ -n $env_path ]]; then
      text="cenv:`basename $env_path`"
      echo -n $text 
  fi
}

prompt_extensions=(prompt_virtualenv prompt_condaenv prompt_git)

build_prompt() {
    # build base prompt
    PROMPT=$(prompt_segment magenta '%n')
    PROMPT+=$(prompt_segment red '@')
    PROMPT+=$(prompt_segment yellow '%m')
    PROMPT+=$(prompt_segment red ':')
    PROMPT+=$(prompt_segment cyan '%0~')

    # build prompt for extensions
    local prompt_ext_text=""
    local sep=""
    for ext in $prompt_extensions; do
        local ext_text=$(eval $ext)
        if [[ -n $prompt_ext_text ]] && [[ -n $ext_text ]]; then
            sep=","
        else
            sep=""
        fi
        prompt_ext_text+=$(prompt_segment green $ext_text $sep)
    done

    # build prompt base - extension separator
    if [[ -n $prompt_ext_text ]]; then
        PROMPT+=$(prompt_segment red '|')
    fi
    PROMPT+=$prompt_ext_text

    # build prompt suffix
    local prompt_nocolor=$(echo ${PROMPT} | perl -pe "s/%\{[^}]+\}//g")
    local prompt_length=${#${(%)prompt_nocolor}}
    if [[ $prompt_length -gt 45 ]]; then
        PROMPT+=$(prompt_segment cyan '\n%{\r%}⇒ ')
    else
        PROMPT+=$(prompt_segment cyan ' ⇒ ')
    fi
}

precmd_functions+=(build_prompt)

HISTSIZE=20000
HISTFILE=~/.zsh_history
SAVEHIST=$HISTSIZE
# hosts=(${=${${(f)"$(cat {/etc/ssh_,~/.ssh/known_}hosts(|2)(N) /dev/null)"}%%[# ]*}//,/ })


### Generic Setup
export LC_ALL='en_US.UTF-8'
export WORKON_HOME=~/.virtualenvs
export EDITOR=vim

if [[ $(uname) = "Darwin" ]]; then
    PATH=$PATH:~/Library/Anaconda/bin
fi

source $DOTCONFDIR/dotconf.sh

### Shell function definition

function _sortimages () {
    SOURCE="$1"
    TARGET_PREFIX="$2"
    DRYRUN=$3

    TARGET=${TARGET_PREFIX}".jpg"
    if [ $(echo "$TARGET_PREFIX" | awk '{print length}') -ge 15 ]; then
        echo mv $SOURCE $TARGET;
        if [ $DRYRUN = 0 ]; then
            mv $SOURCE $TARGET;
            chmod 640 $TARGET;
        fi
    else
        echo "Cannot read Exif information, skipping... $SOURCE"
    fi
}

function sortimages () {
    case $1 in
	-d)
        shift
		for file in $@; do
		    DST=`identify -format "%[Exif:DateTimeOriginal]" $file | head -1 | awk '{print $1":"$2}' | awk -F':' '{print $1$2$3"-"$4$5$6}' | awk -F'.' '{print $1 }' | awk -F'::' '{print $1}'`
            _sortimages $file $DST 0
		done
		;;
	*)
		echo "Rename files"
		echo "Usage: sortimages <options> <file-selection> <suffix>"
		echo "   <file-selection> : for example *.JPG"
		echo "   <suffix>         : rename to "'$date'"-'$time'-suffix.jpg"
		echo "   <options>        : -d   rename the files"
		echo 
		for file in $@; do
		    DST=`identify -format "%[Exif:DateTimeOriginal]" ${file} | head -1 | awk '{print $1":"$2}' | awk -F':' '{print $1$2$3"-"$4$5$6}' | awk -F'.' '{print $1 }' | awk -F'::' '{print $1}'`
            _sortimages $file $DST 1
		done
		;;
esac
}


read -r -d '' REMOTE_CMD << EOF
if [ \$(command -v module 2> /dev/null | wc -l) -gt 0 ]; then
    module load tmux
fi

if [ \$(lsof -U 2> /dev/null | grep ^tmux | wc -l) -gt 0 ]; then
    tmux a
else
    tmux 
fi
EOF

function st () {
    ssh -t $@ ${REMOTE_CMD}
}

compdef st=ssh


### Alias configuration

alias dc='docker-compose --env-file docker-compose.env'
alias dstat='dstat -tclmsgdnpy'
alias glances='glances -b'

if [[ ${+SYSTEM_STACK_DIR} ]]; then
    alias gdc="$(readlink -f $SYSTEM_STACK_DIR)/bin/gdc"
    alias gdca="$(readlink -f $SYSTEM_STACK_DIR)/bin/gdca"
fi

if [[ $(uname) = "Linux" ]]; then
    alias em='emacs -nw'
    alias ec='emacsclient -c'
    alias gl='glances -b'
    alias grep='grep --color'
    alias ls='ls --color'
    alias l='ls -lha --color'
    alias open='xdg-open'
fi

if [[ $(uname) = "Darwin" ]]; then
    PATH=$PATH:~/Library/Anaconda/bin
    alias emacs='/usr/local/opt/emacs/bin/emacs'
    alias em='emacs -nw'
    alias ec='/usr/local/opt/emacs/bin/emacsclient -c'
    alias grep='grep --color=always'
    alias l='ls -lh'
fi


### Conda setup on MacOS

if [[ $(uname) = "Darwin" ]]; then
    source  /Users/mschoengens/Library/Anaconda/etc/profile.d/conda.sh
fi
