#!/bin/sh

# Start an X server for the kiosk user on an available VT.

if [ "$(id -u)" -ne 0 ]; then
  echo "You must be root to launch kiosk mode." 1>&2
  exit 1
fi

datadir=/usr/share/debathena-kiosk
kiosk_user=kiosk@mit
kiosk_group=nogroup
kiosk_home="/home/$kiosk_user"
kiosk_vt_file=/var/run/athena-kiosk-vt
display=99
unset XAUTHORITY

# See if we already have a running kiosk session.
kiosk_vt=$(cat "$kiosk_vt_file" 2>/dev/null)
if [ -n "$kiosk_vt" ]; then
  chvt "$kiosk_vt" && exit 0
fi

# Get the VT to use.
kiosk_vt=$(fgconsole --next-available)
if [ -z "$kiosk_vt" ]; then
  echo "$0: No available VTs" 1>&2
  exit 1
fi

# Remember that we have allocated a VT for a kiosk session.
echo "$kiosk_vt" > "$kiosk_vt_file"

# Set up the kiosk user home directory.
rm -rf "$kiosk_home"
mkdir "$kiosk_home"
cp "$datadir/xinitrc" "$kiosk_home/.xinitrc"
mkdir "$kiosk_home/.gconf"
cp "$datadir/%gconf-tree.xml" "$kiosk_home/.gconf/"
chown -R "$kiosk_user":"$kiosk_group" "$kiosk_home"

# Launch the session on our VT, and wait for it to complete.  This will
# switch back to the current VT upon completion.
openvt -c "$kiosk_vt" -s -w -- su -s /bin/sh -c "startx -- :$display -br \
  -audit 0 -nolisten tcp vt$kiosk_vt" "$kiosk_user"

# Ensure that the VT is deallocated.
deallocvt "$kiosk_vt" > /dev/null 2>&1
rm -f "$kiosk_vt_file"

rm -f "$kiosk_home/.Xauthority"
