#!/bin/bash
# Copyright 2011 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

# first param - autologin user
XUSER=${1:-guest}
# number of virtual console
TTYNUM=${2:-7}
# number of virtual console
DISPLAYNUM=${3:-\:0}
MAINLOOP=1

# write pid for init.d/xdm (detect X for this xautologin)
echo $BASHPID >/var/run/bash.pid

# function for kill X server by TERM,INT,QUIT signals
killXserver()
{
    KILLXPID=$XPID
    XPID=
    MAINLOOP=
    # kill X by TERM
    [[ -d /proc/$KILLXPID ]] && kill $KILLXPID &>/dev/null
    # wait 5 sec
    for i in {0..5}
    do
        [[ -d /proc/$KILLXPID ]] || break
        sleep 1
    done
    WAITRELOGIN=
    # kill X by -KILL
    [[ -d /proc/$KILLXPID ]] && kill -KILL $KILLXPID &>/dev/null
}

trap killXserver SIGTERM SIGINT SIGQUIT

# rerun x session for XUSER while not shutdown and bash not receivce TERM
HOMEDIR=`getent passwd $XUSER | awk -F: '{ print( $6 ); }'`
[[ -d $HOMEDIR ]] || mkdir $HOMEDIR
# export display num
export DISPLAY=${DISPLAYNUM}
export XAUTHORITY=$HOMEDIR/.Xauthority

WAITRELOGIN=7
while id $XUSER &>/dev/null && 
       [[ -n $MAINLOOP ]] &&
       [[ "$(rc-status -r)" != "shutdown" ]]
do
    # disable relogin by fourth param
    if [[ "$4" == "off" ]];then
        MAINLOOP=
    fi
    # prepare user xauthority
    mcookie | sed -e "s/^/add ${DISPLAYNUM} . /" | xauth -f $XAUTHORITY -q
    chown $XUSER. $XAUTHORITY
    chmod 600 $XAUTHORITY
    # perform user profile setting up
    X ${DISPLAYNUM} -auth $XAUTHORITY vt${TTYNUM} -noreset &
    XPID=$!
    env USER=${XUSER} /usr/share/calculate/xdm/xdm --login || break
    # write pam enviroment for pam_ck_connector
    cat >/home/${XUSER}/.pam_environment <<EOF
CKCON_DISPLAY_DEVICE=
CKCON_X11_DISPLAY_DEVICE=/dev/tty${TTYNUM}
CKCON_X11_DISPLAY=${DISPLAYNUM}
EOF
    # registry user in utmp and wtmp
    sessreg -a -l ${DISPLAYNUM} ${XUSER}
    # run x session for user XUSER in background
    su - ${XUSER} -c 'source /etc/profile
                    # replace xinit for startx
                    xinit()
                    {
                        # if file is script run it throught bash
                        if file $1 | grep -1 "POSIX shell script"
                        then
                            /bin/bash $*
                        else
                            $*
                        fi
                    }
                    # run script start xsession
                    source /usr/bin/startx' &
    # wait for right work trap SIGTERM
    XSESSIONPID=$!
    while [[ -d /proc/$XSESSIONPID ]] &&
       [[ "$(rc-status -r)" != "shutdown" ]]
    do
        sleep 1
    done
    # remove user from utmp and wtmp
    sessreg -d -l ${DISPLAYNUM} ${XUSER}
    # perform logout scripts for user
    if [[ -n $WAITRELOGIN ]]
    then
        sleep $WAITRELOGIN
    fi
    env USER=${XUSER} /usr/share/calculate/xdm/xdm --logout
    [[ -n $XPID ]] && kill $XPID
    wait $XPID
done

exit 0
