#
# vim:sw=2 ts=8:et sta
#

find_tmux_session() {
  local e server oifs insess lastsess lastdate foundsess founddate curtty

  if [ -z "$TMUX" ]; then
    return
  fi

  server="${TMUX%,*}"
  server="${server%,*}"

  if [ ! -e "$server" ]; then
    return
  fi

  oifs="$IFS"
  IFS="
"
  insess=0
  lastsess=""
  foundsess=""
  founddate=-1
  curtty="${TTY:-$(tty)}"
  e='('

  for x in $(tmux -S "$server" server-info 2> /dev/null) ; do
    if [ $insess -eq 1 ]; then
      case "$x" in
      "Terminals:")
        insess=0
        break
        ;;
      *[0-9]" windows ${e}created "*)
        lastdate="${x#*[0-9] windows ${e}created }"
        lastdate="${lastdate%) *}"
        lastdate=$(date -j -f '%a %b %d %T %Z %Y' "$lastdate" '+%s')
        x="${x%[0-9] windows ${e}created *}"
        x="${x%: *}"
        x="${x#*[0-9]: }"
        lastsess="$x"
        ;;
      *[0-9]": /dev/"*)
        x="/dev/${x#*[0-9]: /dev/}"
        x="${x%% *}"
        if [ "$x" = "$curtty" ]; then
          if [ $founddate -eq -1 ]; then
            foundsess="$lastsess"
            founddate=$lastdate
          elif [ $lastdate -lt $founddate ]; then
            foundsess="$lastsess"
            founddate=$lastdate
          fi
        fi
        ;;
      esac
    else
      case "$x" in
      "Sessions: ["[0-9]*)
        insess=1
        ;;
      esac
    fi
  done

  [ $founddate -ne -1 ] && echo "$foundsess" || echo "tmux"

  IFS="$oifs"
}

if [ -x "/usr/local/bin/gnuls" ]; then
  alias ls='gnuls -AsCFk --color'
else
  alias ls='/bin/ls -AsCFGk'
fi
alias sls='/bin/ls -AsCFGk'
alias ll='ls -l'
alias l1='ls -1'
alias lsd='ls -d'
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
if [ -x "/usr/local/bin/vim" ]; then
  alias vi='vim'
  export EDITOR='vim'
else
  export EDITOR='vi'
fi
if [ -x "/usr/local/bin/gvim" ]; then
  alias gvi='gvim'
fi
alias more='less'
alias h='history'
alias m='less'
alias cdo='cd "$OLDPWD"'
alias cls='clear'
alias w='w -n'
if [ -f "/etc/DIRCOLORS" -a -x "/usr/local/bin/dircolors" ]; then
  eval $(dircolors /etc/DIRCOLORS)
fi

hist="${SHELL##*/}"
hist="${hist%%-*}"
export HISTFILE="$HOME/.${hist}_history"
unset hist
export SAVEHIST=50000
export HISTFILESIZE=50000
export HISTSIZE=$SAVEHIST

export PKG_DBDIR="/var/db/pkg"
export PKG_TMPDIR="/usr/tmp"
export PORTS_INDEX="${PKG_DBDIR}/INDEX.local"
export PORTS_DBDIR="${PKG_DBDIR}"
export CDROM="/dev/cdrom"
export LSCOLORS="ExGxFxdxCxDxDxCxCxExEx"

export VISUAL="$EDITOR"
export PAGER="less"
export LESS="r"
export BLOCKSIZE="1024k"

export MAKEOBJDIRPREFIX="/usr/obj/$(uname -m)"

export TTY="${TTY:-$(tty)}"

prompt_color=33
prompt_add=""

case "$TERM" in
  cons25)
    bold=1
    ;;
  *xterm*)
    if [ -n "$DISPLAY" ]; then
      stty erase '^?'
    fi
    bold=1
    ;;
  screen)
    bold=1
    if [ -n "$TMUX" ]; then
      prompt_color=36
      prompt_add=":$(find_tmux_session)"
    elif [ -n "$STY" ]; then
      prompt_color=36
      prompt_add=":${STY#*.}"
    fi
    ;;
  *)
    bold=2
    ;;
esac

prompt_add="${prompt_add} (${TTY##*/})"

oifs="$IFS"
export IFS=";"
for x in $(stty -a | grep ' erase[0-9]\? = ') ; do
  y="'${x##*= }'"
  x="${x%% =*}"
  x="${x##*[^a-zA-Z0-9]}"
  case "$x" in
    erase)
      erase="$y"
      ;;
    erase2)
      erase2="$y"
      ;;
  esac
done

export IFS="$oifs"

if [ "${#erase}" -gt 0 -a "${#erase2}" -gt 0 ]; then
  if [ "$erase" != "${erase2}" ]; then
    eval stty erase2 $erase
  fi
fi
unset oifs erase erase2

case "${SHELL##*/}" in
  *bash*)
    shopt -s histverify
    set -o physical
    case "$bold" in
      0 | 1)
        export PS1="\[\033[${bold};${prompt_color}m\][\[\033[0m\]\u\[\033[${bold};${prompt_color}m\]@\[\033[0m\]\h${prompt_add} \W\[\033[${bold};${prompt_color}m\]]\[\033[0m\]\[\033[1;${prompt_color}m\]\\$\[\033[0m\] "
        ;;
      *)
        export PS1='[\u@\h'${prompt_add}' \W]\$ '
        alias ls='sls'
        ;;
    esac
    case "$TERM" in
      *xterm*)
        export PS1='\[\033]0;'${SHELL}' - \u@\h'${prompt_add}' : $PWD\007\]'$PS1
        ;;
    esac
    [ -f /etc/inputrc ] && export INPUTRC="/etc/inputrc"
    ;;
  *zsh*)
    bindkey -e
    case "$TERM" in
      *xterm*)
        precmd() {
          print -Pn "\e]0;${SHELL} - %n@%m : ${PWD}\a"
        }
        bindkey "^[[3~" delete-char-or-list
        ;;
      *cons25*)
        bindkey "^?" delete-char-or-list
        ;;
    esac
    case "$bold" in
      0 | 1)
        export PS1="$(print "%{\e[${bold};${prompt_color}m%}[%{\e[0m%}%n%{\e[${bold};${prompt_color}m%}@%{\e[0m%}%m${prompt_add} %C%{\e[${bold};${prompt_color}m%}]%{\e[0m%}%{\e[1;${prompt_color}m%}%#%{\e[0m%}") "
        ;;
      *)
        export PS1="[%n@%m${prompt_add} %C]%# "
        alias ls='sls'
        ;;
    esac
    bindkey "$(echotc kl)" backward-char
    bindkey "$(echotc kr)" forward-char
    bindkey "$(echotc ku)" up-line-or-history
    bindkey "$(echotc kd)" down-line-or-history
    bindkey "^U" backward-kill-line
    #cons25
    bindkey "^[[H" beginning-of-line
    bindkey "^[[F" end-of-line
    #rxvt
    bindkey "^[[7~" beginning-of-line
    bindkey "^[[8~" end-of-line
    #screen
    bindkey "^[[1~" beginning-of-line
    bindkey "^[[4~" end-of-line
    bindkey "^[[A" history-search-backward
    bindkey "^[[B" history-search-forward
    set +o AUTO_LIST
    set -o BASH_AUTO_LIST
    set -o CHASE_LINKS
    set -o APPEND_HISTORY
    set -o HIST_VERIFY
    set +o PROMPT_CR
    set -o NOHUP
    set -o RM_STAR_SILENT
    set -o HIST_FIND_NO_DUPS
    set -o HIST_IGNORE_ALL_DUPS
    set -o HIST_IGNORE_DUPS
    set -o HIST_SAVE_NO_DUPS
    compctl -g "${PKG_DBDIR:-/var/db/pkg}/*(/:t)" pkg_delete pkg_deinstall portupgrade portmaster
    compctl -g "${PKG_DBDIR:-/var/db/pkg}/*(/:t)" -t+ -f pkg_info
    compctl -/ cd chdir dirs pushd
    if [ -n "$ZSH_COMPSYS" -a "$ZSH_COMPSYS" != "0" ]; then
      autoload -U compinit
      compinit
      _rehash() { ((CURRENT == 1)) && builtin rehash; return 1; }
      zstyle ':completion:::::' completer _rehash _complete _approximate
    else
      _rehash() { builtin rehash; unset reply; }
      compctl -C -K _rehash + -c -tn
      compctl -D -f + -x 'N[-1,=:]' -f -tn
    fi
    ;;
  *sh*)
    set -o emacs
    set -o physical
    alias history='fc -l'
    export USER="${USER:-$(id -un)}"
    export HOSTNAME="${HOSTNAME:-$(hostname)}"
    sh_prompt_add="$prompt_add"
    if [ $(id -u) -eq 0 ]; then
      sh_prompt_char='#'
    else
      sh_prompt_char='$'
    fi
    _cd() {
      local npwd

      builtin cd "$@" || return $?
      npwd="${PWD##*/}"
      case "$npwd" in
        '')
          npwd="/"
          ;;
        *)
          [ "${PWD#*/}" = "$npwd" ] && npwd="$PWD"
          ;;
      esac
      export PS1="[${USER}@${HOSTNAME%%.*}${sh_prompt_add} $npwd]${sh_prompt_char} "
      return 0
    }
    case "$TERM" in
      *xterm*)
        cd() {
          _cd "$@" || return $?
          printf "\033]0;${SHELL} - ${USER}@${HOSTNAME%%.*} : ${PWD}\007"
          return 0
        }
        ;;
      *)
        alias cd='_cd'
        ;;
    esac
    alias chdir='cd'
    ;;
esac

unset bold prompt_color prompt_add

mesg y > /dev/null 2>&1
/usr/sbin/kbdcontrol -r fast > /dev/null 2>&1
stty status '^T' > /dev/null 2>&1

alias fexit='export HISTFILE=/dev/null ; exit'

cd .
