#/* 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.20'

# 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 10000
#ulimit -u 1000 # set in .bashrc

# 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"
        return 0
    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"
        return 0
    # 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}'"'
        return 0
    # 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
    #vlock
fi

# start tmux in normal mode
__autostart_tmux

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