#!/bin/sh
# a "singleton" script to use instead of startx,
# possibly to be *sourced* in one's shell profile
# (so logout works and no extra shells are left)
#
# 2008, Michael Shigorin <mike@altlinux.org>
# public domain

# NB: exit/return might break xinitrc disregarding of $SHLVL
if [ -z "$DISPLAY" ]; then

# find an existing session and switch there,
# or failing that, try to start a new one
prefix="/tmp/.X11-unix"
logfix="/var/log/Xorg"	# XFree86 is next to nonexistent in 2008...
group="`id -gn`"	# won't do *dm (root there)

# print display number (e.g. 2)
# there might be multiple logins already, use first as a better habit
find_x()
{
	find "$prefix" -group "$1" -name "X[0-9]*" \
	| sort -n \
	| head -1 \
	| sed "s,^$prefix/X,,"
}

# print VT number (e.g. 9)
# a socket guarantees a log
find_vt()
{
	sed -n "s,^.* VT number \([0-9]\+\),\1,p" "$logfix.$1.log"
}

[ -n "$group" ] || startx	# ouch!  X would probably break too

x="`find_x "$group"`"
[ -n "$x" ] || { startx; exit; }	# start new one, don't leave shell after

vt="`find_vt "$x"`"
[ -z "$vt" ] || { chvt "$vt"; exit; }		# use existing session

# weird, you probably want your shell by this time
fi
# already there, just lend a shell
