#!/bin/sh


_l3_start()
{
    L3_TTY=`tty` 
    proc_on_the_term=`w | grep "${L3_TTY##/dev/}" | awk '{print $8;}'`
    # freeBSD: 
    [ -n "$bsd" ] && \
    proc_on_the_term=`w | grep "${L3_TTY##/dev/tty}" | awk '{print $6;}'`

    if [ -n "$proc_on_the_term" ] && echo $proc_on_the_term | grep -qv script
    then
        _l3_start_session
        _l3_run_script
    else
        _l3_env
        _l3_prompt
    fi
}

_l3_env()
{
    trap _l3_close_session 2
    trap _l3_close_session EXIT
    true
}

_l3_prompt()
{
#export PS1='\[v2_$(date +%s)_$?_$PWD_\!_\033[1024D\033[K\][\u@\h:\W]\$ '
    export PS1='\[`
    a="$?";
    HIDDEN=$([ "$a" = 0 ] || echo -n ^"$a")$(echo -n _${UID}_)$(echo -n _$$_)$(date\
        +"%j$(cat ${LMHOME}/lab 2>/dev/null) %H:%M:%S");
    echo $HIDDEN`\033[50D\033[K\][\u@\h:\W]\$ '
}

_l3_start_session()
{
    export L3_SESSION_ID=${L3_TTY##*/}-$$
    export L3_HOME=~/.lilalo/
    mkdir -p $L3_HOME

    uname -a | grep -qi bsd && bsd=yes
    parent=`cat /proc/$PPID/cmdline 2> /dev/null`
    system=`uname -rs`
    login_from=`who | grep "${tty##/dev/}" | awk '{print $6;}' | tr -d '()'`
    #[ -n "$bsd" ] && login_from="" #FIXME!
    start_time=`date +%s`
    hostname=`hostname -f 2> /dev/null`
    [ -n "$bsd" ] && hostname=`hostname`

    cat <<INFO > $L3_HOME/$L3_SESSION_ID.info
<session>
    <local_session_id>$L3_SESSION_ID</local_session_id>
    <hostname>$hostname</hostname>
    <user>$USER</user>
    <uid>$UID</uid>
    <login_from>$login_from</login_from>
    <tty>$tty</tty>
    <system>$system</system>
    <parent>$parent</parent>
    <ppid>$PPID</ppid>
    <pid>$$</pid>
    <start_time>$start_time</start_time>
</session>
INFO

    unset parent system login_from start_time hostname 
}

_l3_run_script()
{
    uname -a | grep -qi bsd && bsd=yes
    flush="-f"                          #linux
    [ -n "$bsd" ] && flush="-t 0"       #freebsd
    exec script $flush -q $L3_HOME/${L3_SESSION_ID}.script
}

_l3_close_session()
{
    ( 
        echo '<history>'
        history | sed 's/&/\&amp;/; s/</\&lt;/g; s/>/\&gt;/g'
        echo '</history>'
    ) >> $L3_HOME/$L3_SESSION_ID.info
}