if [ "$USER" = "root" ] && [ -z "$SSH_USER" ] && [ ! -z "$SSH_CLIENT" ] && [ -r /var/log/rsyslog/local/sshd/sshd.info.log ]; then
    # retrieve key name from current user (usefull with Zephir, everybody use root user)
    IP=$(echo $SSH_CLIENT| cut -d' ' -f 1)
    PORT=$(echo $SSH_CLIENT| cut -d' ' -f 2)
    CONN=$(grep "Accepted publickey for root from $IP port $PORT ssh2: " /var/log/rsyslog/local/sshd/sshd.info.log | tail -n 1)
    KEY=$(echo $CONN | awk -F': ' '{ print $3 }')
    KEY_TYPE=$(echo $KEY | cut -d' ' -f 1)
    KEY_VAL=$(echo $KEY | cut -d' ' -f 2)
    if [ ! -z "$KEY_VAL" ]; then
        SSH_USER_TMP=$(ssh-keygen -lf /root/.ssh/authorized_keys | grep "$KEY_VAL" | grep " ($KEY_TYPE)"$ | tail -n 1 | cut -d' ' -f 3)
        if [ ! -z "$SSH_USER_TMP" ]; then
            SSH_USER=$SSH_USER_TMP
            export SSH_USER
            readonly SSH_USER
        fi
    fi
fi

trap_cmd_var() {
    if [ ! "${BASH_EXECUTION_STRING}-" = "-" ] && [ "${BASH_ARGV[@]}-" = "-" ]; then
        CMD=${BASH_EXECUTION_STRING}
    fi
    logcommand "$CMD"
}

trap_cmd_history() {
    CMD=$(fc -ln -1|sed -e "s/^[ \t]*//g")
    logcommand "$CMD"
}

logcommand() {
    R_CMD=$1
    [ -z "$R_CMD" ] && return
    R_TTY=$(tty)
    R_USER=$USER
    if [ ! -z "$SUDO_USER" ]; then
        R_REMOTE_USER=$SUDO_USER
    elif [ ! -z "$SSH_USER" ]; then
        R_REMOTE_USER=$SSH_USER
    else
        R_REMOTE_USER=$USER
    fi
    R_SSH_CLIENT=$SSH_CLIENT
    R_HISTORY=$SCREEN_HISTORY
    R_PPID="$$"
    R_PWD=$PWD
    /usr/bin/logger -t history "\"$R_USER\" \"$R_REMOTE_USER\" \"$R_SSH_CLIENT\" \"$R_HISTORY\" \"$R_TTY\" \"$R_PPID\" \"$R_PWD\" \"$R_CMD\""
}
if [ -z "$PS1" ]; then
    trap 'trap_cmd_var' DEBUG
else
    trap 'trap_cmd_history' DEBUG
fi
