#!/bin/bash
# Single Xwindow/KDE startup script
# (C) Klaus Knopper Jun 2001

USER=knoppix

PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/X11R6/bin:/usr/local/bin:."
export PATH

umask 022

CRE="
[K"
BLUE="[1;34m"
NORMAL="[1;39m"

RUNLEVEL5=""
case "$(runlevel)" in *\ 5) RUNLEVEL5="true" ;; esac

XMODULE=""
[ -f /etc/sysconfig/xserver ] && . /etc/sysconfig/xserver
[ -f /etc/sysconfig/knoppix ] && . /etc/sysconfig/knoppix

[ -n "$BACKGROUND" -a -e "$BACKGROUND" ] || BACKGROUND="-background black -default"

# See how we were called.
case "$1" in
  start)
rm -f /etc/sysconfig/xsession-restart

if [ -n "$RUNLEVEL5" ]; then
# Don't start X in the default runlevel 5 if brltty or sbl are running!
BPID="$(pidof brltty 2>/dev/null || pidof sbl 2>/dev/null)"
[ "$?" = "0" ] && exit 0
fi

realmem(){
while read type mem relax; do
 case "$type" in MemTotal*) echo "$mem";; esac
done </proc/meminfo
}

echo "${CRE}${BLUE}Executing $0 $1:${NORMAL}"
REALMEM="$(realmem)"
if [ -n "$REALMEM" -a "$REALMEM" -lt 14000 ]
then
echo "${BLUE}$0: ${RED}Sorry, You need at least 16 Megs of RAM to start the X Window system.${NORMAL}"
echo "${BLUE}$0: ${RED}Exiting now.${NORMAL}"
exit 1
fi

echo "-----------------------------------------------------------------------"
echo "	${NORMAL}Starting single X-Window session for User $USER.            "
echo "	Please stand by a few seconds while the optimal configuration        "
echo "	is being determined.                                                 "
if [ -n "$RUNLEVEL5" ]
then
echo ""
echo "After this session terminates, the system will automatically shut down."
fi
echo "-----------------------------------------------------------------------"

ACCEL=""
XOPTIONS=""
# We used to support only 75dpi, but this is too small for larger displays
# DPI="-dpi 75"
DPI=""
NORESET=""
[ -n "$XSERVER" ] && type -a "$XSERVER" >/dev/null 2>&1 && ACCEL="$XSERVER"
[ -L /etc/X11/X ] && ACCEL="$ACCEL /etc/X11/X"

# Try to find and load an agp and drm module for this graphics card
KVER="$(uname -r)"

loadagp(){
# Kernel 2.6: Load specific AGPGART module(s)
 case "$(cat /proc/cmdline)" in *noagp*) ;; *)
  echo -n "${BLUE}Probing/Loading AGP modules...${NORMAL}"
  modprobe agpgart >/dev/null 2>&1
# Should not be needed anymore in Kernel 2.6, but some agp bridges are still
# not detected automatically. :-( -KK
  for i in /lib/modules/"$KVER"/kernel/drivers/char/agp/*; do
    # ac-knx opt
    #module="${i##*/}"; module="${module%%.*}"; modprobe ${module} >/dev/null 2>&1
    module="${i##*/}"; module="${module%%.*}"; modprobe ${module} >/dev/null 2>&1 &
  done
  echo ""
 ;;
esac
}

# Remove unused AGP modules
unloadagp(){
# Kernel 2.6: Load specific AGPGART module(s)
 case "$(cat /proc/cmdline)" in *noagp*) ;; *)
  echo -n "${BLUE}Unloading unneeded AGP modules...${NORMAL}"
  while read m relax; do
   case "$m" in *_agp) rmmod "$m" >/dev/null 2>&1; ;; esac
  done </proc/modules
  echo ""
;;
 esac
}

# Load modules for all AGP chipsets (see above)
loadagp

if [ -n "$XMODULE" ]; then
# All kernels: Load drm module
for i in /lib/modules/"$KVER"/kernel/drivers/char/drm/*; do
# ac-knx opt
#case "$i" in *$XMODULE*) module="${i##*/}"; module="${module%%.*}"; modprobe ${module} >/dev/null 2>&1 ;; esac
case "$i" in *$XMODULE*) module="${i##*/}"; module="${module%%.*}"; modprobe ${module} >/dev/null 2>&1 & ;; esac
done
fi

# ac-knx opt
while [ true ] ; do
  ps ax | grep -v grep | grep modprobe >/dev/null 2>&1
  [ "$?" != "0" ] && break;
  usleep 100000
done

echo -n "${BLUE}Starting the X Window System...${NORMAL}"

for X in $ACCEL vesa fbdev
do
# Use customized version of XF86Config for old servers
XCONFIG="-xf86config /etc/X11/XF86Config"
BPP="-bpp"
case "$X" in
*Xorg*) XCONFIG="-config /etc/X11/xorg.conf"; BPP="-depth"; NORESET="-noreset"; ;;
vesa|fbdev)
	for i in xserver knoppix; do echo 'XSERVER="Xorg"' >> /etc/sysconfig/$i; echo 'XMODULE="'"$X"'"' >> /etc/sysconfig/$i; done
	echo "${NORMAL}"
	echo -n "${BLUE}Retrying with Server ${GREEN}Xorg(${YELLOW}$X${GREEN})${NORMAL} "
	rm -f /etc/X11/xorg.conf
	mkxorgconfig >/dev/null 2>&1
	X=Xorg ; XCONFIG="-config /etc/X11/xorg.conf"; BPP="-depth"; NORESET="-noreset"; XOPTIONS=""
	;;
esac
# Try hwsetup-generated flags first, if present
$X $NORESET $XCONFIG $XOPTIONS $DPI :0 2>/dev/null && break
# Mostly failsafe probe fallbacks
# Some cards prefer 16 bit, especially when low on mem or not SVGA,
# so try this first.
if $X $NORESET $XCONFIG $BPP 16 $DPI :0 2>/dev/null || \
   $X $NORESET $XCONFIG $BPP 24 $DPI :0 2>/dev/null || \
   $X $NORESET $XCONFIG $BPP 32 $DPI :0 2>/dev/null || \
   $X $NORESET $XCONFIG $BPP  8 $DPI :0 2>/dev/null; then break; fi
echo -n "${BLUE}.${NORMAL}"
done &

# ac-knx opt
#sleep 2
#
## Wait for X-Server startup
#for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#do
#found="true"
## Startup Logo
## DISPLAY=:0 xloadimage -center -onroot -border black \
#DISPLAY=:0 xloadimage -onroot -fullscreen -shrink -smooth -border black -quiet $BACKGROUND >/dev/null 2>&1 && break
#found="false"
#sleep 1
timeout=22000000
while [ 0 -lt $timeout ]; do
  found="true"
  DISPLAY=:0 xset q >/dev/null 2>&1 && break
  found="false"
  usleep 100000
  let timeout=$timeout-100000
done
echo ""

# Unload modules for non-existing AGP chipsets (see above)
unloadagp

if [ "$found" = "false" ]
then
  echo "${RED}Error: No suitable X-Server found for your card.${NORMAL}"
  exit 1
# ac-knx opt
else
  DISPLAY=:0 xloadimage -onroot -fullscreen -shrink -smooth -border black -quiet $BACKGROUND >/dev/null 2>&1 &  
fi

# FIXME: Move to others

rm -f /etc/sysconfig/xsession-commands
touch /etc/sysconfig/xsession-commands
chown $USER.$USER /etc/sysconfig/xsession-commands

# For KDE >= 3.5, /tmp/.ICE-unix MUST be owned by root, and MUST be writable for users.
# So, we need to create it right here before starting our Xsession.
mkdir -m 1777 -p /tmp/.ICE-unix

# Now, start the user's Xsession
# (/etc/X11/Xsession.d/45xsession will be called at some point,
# which does everything in Knoppix)
su -c "DISPLAY=:0 exec /etc/X11/xinit/xinitrc" - $USER >/dev/null 2>&1
RC="$?"

XSESSION_COMMAND=$(</etc/sysconfig/xsession-commands) # Read in what kde / ... told us.

# After xsession exits, end X-Server
for i in $ACCEL $X $XSERVER Xorg XF86_SVGA; do
killall -TERM $i 2>/dev/null && break
done
echo ""
echo -n "${CRE}${BLUE}X Window session terminated "
if [ "$RC" = "0" ]
then
echo "without errors."
NEXT_RUNLEVEL=0

if [ -n "$XSESSION_COMMAND" ]
then
 case "$XSESSION_COMMAND" in
  shutdown*halt*)
   NEXT_RUNLEVEL=0
  ;;
  shutdown*reboot*)
   NEXT_RUNLEVEL=6
  ;;
  kde_restart)
   [ ! -f /etc/sysconfig/xsession-restart ] && exec $0 start
  ;;
esac
fi

if [ -n "$RUNLEVEL5" -a ! -f /etc/sysconfig/xsession-restart ]
then
echo "Shutting down.${NORMAL}"
# Play informational sound if soundcore module present
# (checking /dev/sndstat is unreliable)
OGGPLAY=/usr/bin/ogg123
PLAY=/usr/bin/wavp
[ -x "$PLAY" ] || PLAY=/usr/bin/play-sample
[ -x "$PLAY" ] || PLAY=/usr/bin/play
if [ -x "$OGGPLAY" -a -f /usr/share/sounds/shutdown.ogg ]; then
case "$(</proc/modules)" in *sound*|*snd_*) { $OGGPLAY -q -p 64 /usr/share/sounds/shutdown.ogg >/dev/null 2>&1 & } ; sleep 7 ;; esac
elif [ -f /usr/share/sounds/shutdown.wav -a -x "$PLAY" ]; then
case "$(</proc/modules)" in *sound*|*snd_*) { $PLAY /usr/share/sounds/shutdown.wav >/dev/null 2>&1 & } ; sleep 7 ;; esac
fi
init $NEXT_RUNLEVEL
fi
else
echo "with errors."
echo "${RED}Please check $XCONFIG and retry ${CYAN}'$0 start'${RED}.${NORMAL}"
fi
        ;;
  stop)
        # Stop daemons.
	# Don't shutdown if killed by init or manually
        touch /etc/sysconfig/xsession-restart
	for i in $XSERVER XF86_SVGA; do
        killall -TERM $i 2>/dev/null && echo "${BLUE}X-Server shut down.${NORMAL}" && break
	done
        ;;
  restart)
        touch /etc/sysconfig/xsession-restart
	( nohup bash -c "$0 stop; sleep 5; $0 start" & )
        ;;
  *)
        echo "${RED}Usage: xsession {start|stop}${NORMAL}"
        exit 1
esac

exit 0
