#!/bin/sh
# ~/.profile

PATH=$HOME/.local/bin:/usr/local/bin:${PATH:-/usr/bin:/bin}:/usr/sbin:/sbin
ENV=$HOME/.shrc
BASH_ENV=$HOME/.zshenv
[ -n "$RSYNC_RSH" ] || RSYNC_RSH='ssh -ax'
export PATH ENV BASH_ENV RSYNC_RSH

if [ -r "$HOME/.env.local" ]; then
  eval "$(command grep '^[A-Z].*=' "$HOME/.env.local"|sed -e 's/^/export /')"
fi

[ ! -r "$HOME/.profile.local" ] || . "$HOME/.profile.local"

if [ -z "$PAGER" ] && type less >/dev/null 2>&1; then
  PAGER=less
  export PAGER
fi
LESS="FXRq#10"
if [ -z "$LESSOPEN" ] && type lesspipe >/dev/null 2>&1; then
  LESSOPEN='|lesspipe %s'
elif [ -z "$LESSOPEN" ]; then
  LESSOPEN='|"$HOME/.lessfilter" %s'
fi
if [ -z "$VISUAL" ]; then
  type vim >/dev/null 2>&1 && VISUAL=vim || VISUAL=vi
fi
EDITOR=$VISUAL
BROWSER="tpope browser"
export LESS LESSOPEN VISUAL EDITOR

IFS=:
newpath=.git/safe/../../bin:$HOME/.local/bin
for dir in $PATHPREPEND $PATH; do
  case :$newpath: in
    *:$dir:*) ;;
    *) [ -z "$dir" -o ! -d "$dir" ] || newpath=$newpath:$dir ;;
  esac
done
PATH=$newpath

unset IFS dir newpath

if [ -t 1 ] && expr "$-" : '.*i' >/dev/null; then
  if [ -f "$HOME/.hushlogin" ]; then
    if [ -x /usr/bin/finger ]; then
      finger $LOGNAME | grep '^New mail' >/dev/null && echo "You have new mail."
    elif [ -f "$MAIL" ]; then
      find "$MAIL" -newerma "$MAIL" -exec echo 'You have new mail.' \;
    fi
  fi

  if [ ! -f "$HOME/. tpope" ]; then
    echo 'Performing an initial "tpope setup"'
    tpope setup
  elif [ -x /usr/games/fortune ] && [ "$SHLVL" -le 1 -a \( -z "$SSH_TTY" -o "$TERMCAP" \) ]; then
    /usr/games/fortune
  fi

  tpope cron --login
fi

# ==============================================================================
# vi settings: set show-match auto-indent always-redraw shift-width=4
#export EXINIT="se sm ai redraw sw=4"

# Configure the shell to load .shrc at startup time.
# This will happen for every shell started, not just login shells.
export ENV=$HOME/.shrc

# --- login routines ---

# create a user-owned  dir where
# to store temporary files
dir=/tmp/$(id -u)
if [ ! -d "$dir" ]; then
    mkdir -p $dir
    /sbin/chown -R $(whoami):$(id -gn) $dir
    chmod -R 0700 $dir
fi
export XDG_RUNTIME_DIR=${dir}
export TMPDIR=${XDG_RUNTIME_DIR}
unset dir

# Create a directory owned by the user under /tmp,
# and make ~/.cache a symbolic link to it.
#
CACHE="${HOME}/.cache"
[ -z $CACHE ] || rm -rf $(readlink $CACHE)
dir=$(mktemp -d /tmp/${LOGNAME}.XXXXXX)
ln -sf ${dir} $CACHE
unset dir


# mailbox notifications
if [ -x /usr/bin/biff ]; then
  biff y 2> /dev/null
  echo ''
fi

# give a fortune cookie
[ -x /usr/games/fortune ] && /usr/games/fortune -aes
echo ''

# display current date
echo ''; echo -n 'To days date is: '; date

# start ssh agent
if [ -x /usr/pkg/bin/keychain ]; then
  keychain id_ed25519
  . ${HOME}/.keychain/$(hostname)-sh
  echo ''
fi

# lauch tmux by default
if command -v tmux &> /dev/null && [ -z "$TMUX" ]; then
  tmux attach -t default || tmux new -s default
fi
