#/* vim: set filetype=sh : */
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.
#
# Use sh-compatible syntax.
# To run bash on login-shell mode use: bash --login
#
# dimio (dimio.org)
# http://dimio.org/bash-born-again-shell-obolochka-komandnoj-stroki.html
# VERSION='0.21'

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
umask 077
#ulimit -u 1000 # set in .bashrc

ERR_NOTMUX=141
ERR_TMUXRUN=142
ERR_TMUXINSCREEN=143

# Autostart tmux on login
__autostart_tmux() {
    # $( type -p ) - built-in in sh or bash only?
    #TMUX_BIN="$( whereis tmux | cut -d " " -f 2 )"
    # which versions different output format
    TMUX_BIN="$( which tmux 2> /dev/null )"
    if [ -z "${TMUX_BIN}" ]; then
        echo "Tmux not found"
        exit "${ERR_NOTMUX}"
    fi

    TMUX_AS_SESS_NAME="$(echo "${USER}" | cut -c '1-3')"
    # return empty line if specified session exist or return 1
    TMUX_AS_SESS_RUN="$( tmux has-session -t "${TMUX_AS_SESS_NAME}" &> /dev/null || echo "$?" )"
    #TMUX_AS_DAEMON_MODE="$1" # $1 == "-d" or " "
    #TMUX_AS_EXIT="$2" # "return 0" or "exit 0"

    # do not attach automatically to tmux session if login on local XTerm
    if [ -z "${TMUX_AS_SESS_RUN}" ] && [ -z "${SSH_TTY}" ] && [ "${TERM}" = "xterm" ]; then
        echo "Tmux: running, not attached on local XTerm"
        exit "${ERR_TMUXRUN}"
    # do not run tmux automatically in another tmux (or screen)
    # in exists tmux session shell be started on non-login mode and .profile not used
    # (see set -g default-command "${SHELL}" in tmux.conf)
    elif [ -n "${TMUX}" ] || [ "${TERM}" = "screen" -o "${TERM}" = "screen-256color" ]; then
        echo 'Tmux: not be running in another terminal multiplexer "'${TERM}'"'
        exit "${ERR_TMUXINSCREEN}"
    # attach to existed tmux session or create it and exit login-shell; or print error message
    else
        ((tmux has-session -t "${TMUX_AS_SESS_NAME}" && exec tmux attach-session -t "${TMUX_AS_SESS_NAME}") || (tmux new-session -d -s "${TMUX_AS_SESS_NAME}" && exec tmux attach-session -t "${TMUX_AS_SESS_NAME}")) && exit 0;
        echo "Tmux: autostart failed: $?"
    fi
}

# Autostart X server (prefered WM or DE see in ~/.xinitrc)
if [ -z "${DISPLAY}" ] && [ "$(tty)" = "/dev/tty1" ]; then
    exec startx
fi

# Start tmux in normal mode if login on tty2
if [ "$(tty)" = "/dev/tty2" ]; then
    __autostart_tmux
fi

# If runnign bash
if [ -n "${BASH_VERSION}" ]; then
    # source .bashrc if it exists
    if [ -r "${HOME}/.bashrc" ]; then
        source "${HOME}/.bashrc"
    fi
fi