#! /bin/sh

. $TS_GLOBAL

XAUTHHOME=$HOME
HOME=/tmp
X_PATH=/usr/X11R6
X_OPTIONS=/tmp/x_options
X_PORT=/tmp/x_port
X_AUTO=$HOME/xorg.conf.new
X_MONITOR_OPTIONS=/tmp/x_monitor_options

build_command ()
{
  X_CMD="$X_SERVER :$DISPLAY_NUMBER"
  if [ -e /tmp/X_TERMINATE ] ; then
	  X_CMD="$X_CMD -terminate"
  fi

  # Define Font Paths
  X_FONT="$X_PATH/lib/X11/fonts"
  if [ -n "$SCREEN_X_FONT_SERVER" ]; then
    if [ "$X_SERVER" != "Xvesa" ]; then
	X_CMD="$X_CMD -fp $X_FONT/misc,tcp/$SCREEN_X_FONT_SERVER"
    else
	X_CMD="$X_CMD -fp tcp/$SCREEN_X_FONT_SERVER"
    fi
  else
    for filename in `ls $X_FONT`
    do
	if [ -e $X_FONT/$filename/fonts.dir ] ; then
		if [ -z "$FONTPATH" ] ; then
			FONTPATH="$X_FONT/$filename"
		else
			FONTPATH="$FONTPATH,$X_FONT/$filename"
	        fi
    	fi
    done
    X_CMD="$X_CMD -fp $FONTPATH"
  fi

  [ "$X_SERVER" = "Xorg" ] && X_CMD="$X_CMD -depth $SCREEN_COLOR_DEPTH \
                                               -xkbmap $KEYBOARD_MAP \
					       -xf86config /etc/X11/XF86Config-$DISPLAY_NUMBER"
  [ "$X_SERVER" != "Xorg" ] && [ "$X_SERVER" != "Xvesa" ] && \
             X_CMD="$X_CMD -bpp $SCREEN_COLOR_DEPTH -xkbmap $KEYBOARD_MAP \
	     -xf86config /etc/X11/XF86Config-$DISPLAY_NUMBER"
  [ "$X_SERVER" = "Xvesa" ] && X_CMD="$X_CMD -screen $SCREEN_RESOLUTION"x"$SCREEN_COLOR_DEPTH"

  if [ -n "$DUALHEAD" ] ; then
	# The keybdev driver can interfer with dual head support and needs to be removed
	if lsmod | grep keybdev > /dev/null 2>&1 ; then
		rmmod keybdev
	fi
	# The apm module causes the second screen to crash when using dual head
	if lsmod | grep apm > /dev/null 2>&1 ; then
		rmmod apm
	fi
  	if [ "$X_SERVER" = "Xorg" ] && [ "$POSITION" -ge 2 ] ; then
		X_CMD="$X_CMD -novtswitch -sharevts"
 	fi
  fi
}


parse_xconfig ()
{
    X_CONFIG=/etc/X11/XF86Config-$DISPLAY_NUMBER
    echo s/\$SCREEN_RESOLUTION/$SCREEN_RESOLUTION/g > /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_HORIZSYNC/$SCREEN_HORIZSYNC/g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_VERTREFRESH/$SCREEN_VERTREFRESH/g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_BLANK_TIME/$SCREEN_BLANK_TIME/g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_STANDBY_TIME/$SCREEN_STANDBY_TIME/g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_SUSPEND_TIME/$SCREEN_SUSPEND_TIME/g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$SCREEN_OFF_TIME/$SCREEN_OFF_TIME/g >> /tmp/script$DISPLAY_NUMBER
    echo s\@\$MOUSE_PROTOCOL@$MOUSE_PROTOCOL@g >> /tmp/script$DISPLAY_NUMBER
    echo s\@\$MOUSE_DEVICE@$MOUSE_DEVICE@g >> /tmp/script$DISPLAY_NUMBER
    echo s\@\$KEYBOARD_DEVICE@$KEYBOARD_DEVICE@g >> /tmp/script$DISPLAY_NUMBER
    echo s\@\$MOUSE_RESOLUTION@$MOUSE_RESOLUTION@g >> /tmp/script$DISPLAY_NUMBER
    echo s\@\$MOUSE_SENSITIVITY@$MOUSE_SENSITIVITY@g >> /tmp/script$DISPLAY_NUMBER
    echo s/\$DISPLAY_NUMBER/$DISPLAY_NUMBER/g >> /tmp/script$DISPLAY_NUMBER
    cat $X_PATH/lib/X11/XF86Config-$1.tpl | sed -f /tmp/script$DISPLAY_NUMBER > $X_CONFIG
    rm /tmp/script$DISPLAY_NUMBER
    return 0
}

xorg_options ()
{
  if [ -n "$1" ] ; then
	(echo $1) |
	while read name option
	do
		echo -e "\tOption \"$name\" \"$option\"" >> $X_OPTIONS
	done
  fi
}

monitor_options ()
{
  if [ -n "$1" ] ; then
	(echo $1) |
	while read name option
	do
		echo -e "\tOption \"$name\" \"$option\"" >> $X_MONITOR_OPTIONS
	done
  fi
}

xorg_autoconfig ()
{
    if [ ! -e $X_AUTO ] ; then
      Xorg -modulepath $X_PATH/lib/X11/modules -configure >/var/log/x.config.log 2>&1
    fi
    X_CONFIG=/etc/X11/XF86Config-$DISPLAY_NUMBER

    # Extra options for X Device

    cat /dev/null > $X_OPTIONS
    xorg_options "$X_DRIVER_OPTION1"
    xorg_options "$X_DRIVER_OPTION2"
    xorg_options "$X_DRIVER_OPTION3"
    xorg_options "$X_DRIVER_OPTION4"
    xorg_options "$X_DRIVER_OPTION5"

    # Extra options for X Monitor

    cat /dev/null > $X_MONITOR_OPTIONS
    monitor_options "$X_MONITOR_OPTION1"
    monitor_options "$X_MONITOR_OPTION2"
    monitor_options "$X_MONITOR_OPTION3"
    monitor_options "$X_MONITOR_OPTION4"
    monitor_options "$X_MONITOR_OPTION5"
	if [ -n "$X_MONITOR_MODELINE" ] ; then
		echo -e "\tModeLine $X_MONITOR_MODELINE" >> $X_MONITOR_OPTIONS
	fi

    if [ -e $X_PATH/lib/X11/vnc_device.tpl ] ; then
	VNC_PATH=$X_PATH/lib/X11
	cat $VNC_PATH/vnc_device.tpl  >> $X_OPTIONS
    fi

    # Manual Settings override autoconfig, however, if manual settings for
    # driver name are wrong, it will drop back to autoconfig

    if [ -e $X_AUTO ] ; then
	let x=-1
	if [ ! -e $X_PORT ] ; then
		echo $x > $X_PORT
	fi
	awk "/Section \"Screen\"/,/EndSection/" $X_AUTO | \
         	 awk '{print $0; if ( /Viewport/ ) print "\t\tModes \"'$SCREEN_RESOLUTION'\""}' \
		 >> $X_CONFIG
	awk "/Section \"Monitor\"/,/EndSection/" $X_AUTO | \
         awk '{print $0; if ( /Section \"Monitor\"/ ) system ( "cat '$X_MONITOR_OPTIONS'")}' | \
		 grep -v -e"HorizSync" -e"VertRefresh" | \
         awk '{print $0; if ( /ModelName/ ) { \
           if ( "'$SCREEN_HORIZSYNC'" ) { print "\tHorizSync '$SCREEN_HORIZSYNC'" } \
           if ( "'$SCREEN_VERTREFRESH'" ) { print "\tVertRefresh '$SCREEN_VERTREFRESH'"} \
         }}' >> $X_CONFIG
    if [ -e "$X_PATH/lib/X11/modules/drivers/$X_DRIVER_NAME"_drv.so ] ; then
	   echo "Section \"Device\"" >> $X_CONFIG
	   echo "Driver \"$X_DRIVER_NAME\"" >> $X_CONFIG
	   echo "Identifier \"Card0\"" >> $X_CONFIG
	   if [ -n "$X_DRIVER_BUSID" ] ; then
		echo "BusID \"$X_DRIVER_BUSID\"" >> $X_CONFIG
	   fi
	   cat $X_OPTIONS >> $X_CONFIG
	   echo "EndSection" >> $X_CONFIG
	else
	   awk "/Section \"Device\"/,/EndSection/" $X_AUTO | \
    	     awk '{print $0; if ( /Section \"Device\"/ ) system("cat '$X_OPTIONS'")}' | \
	     awk 'BEGIN {x='`cat $X_PORT`'} {print $0 ; if ( /httpdir/ ) { y=y+1; \
	     print "\tOption  \"httpport\" \""y+x+5800"\"" }} END { print y+x > "'$X_PORT'"}' >> $X_CONFIG
    fi
	# Some model names are causing a config file to be corrupted,  ModelName isn't required so we are deleting it
	sed -i /ModelName/d $X_CONFIG

	# Checks for and configures dual head support

	if [ "$DUALHEAD" = "ENABLED" ] ; then

		# Auto configures keyboard/mouse support
		if [ -z "$X_KEYBOARD1" ] ; then
		  ls /dev/input/event* > /tmp/devices
      		  if [ -s /tmp/devices ] ; then
			(cat /tmp/devices) |
			while read device
			do
			  if [ "$devicetype" != "`evdev $device 2>&1`" ] ; then
				devicetype=`evdev $device 2>&1`
				if [ -z "$X_KEYBOARD1" ] ; then
					if echo $devicetype | grep eyboard > /dev/null ; then
						X_KEYBOARD1=$device
						echo "X_KEYBOARD1=$device" >> $TS_RUNTIME
					fi
				elif [ -z "$X_KEYBOARD2" ] ; then
					if echo $devicetype | grep eyboard > /dev/null ; then
						X_KEYBOARD2=$device
						echo "X_KEYBOARD2=$device" >> $TS_RUNTIME
					fi
				fi
				if [ -z "$X_MOUSE1" ] ; then
					if echo $devicetype | grep ouse > /dev/null ; then
						X_MOUSE1=$device
						echo "X_MOUSE1=$device" >> $TS_RUNTIME
					fi
				elif [ -z "$X_MOUSE2" ] ; then
					if echo $devicetype | grep ouse > /dev/null ; then
						X_MOUSE2=$device
						echo "X_MOUSE2=$device" >> $TS_RUNTIME
					fi
				fi
			   fi
			done
		  fi
		  rm /tmp/devices
	  	fi

		. $TS_RUNTIME
		if [ -z "$X_MOUSE1" ] ; then
			echo_log "Dual Head session aborted, no 1st mouse found"
			DUALHEAD=""
		fi
		if [ -z "$X_MOUSE2" ] ; then
			echo_log "Dual Head session aborted, no 2nd mouse found"
			DUALHEAD=""
		fi
		if [ -z "$X_KEYBOARD1" ] ; then
			echo_log "Dual Head session aborted, no 1st keyboard found"
			DUALHEAD=""
		fi
		if [ -z "$X_KEYBOARD2" ] ; then
			echo_log "Dual Head session aborted, no 2nd keyboard found"
			DUALHEAD=""
		fi
		if [ -n "$DUALHEAD" ] ; then
		       	if [ "$POSITION" -ge "2" ] ; then
				CONFIGFILE=$X_PATH/lib/X11/XF86Config-Xorg_Head2.tpl
				CONFIGSERVER=$CONFIGFILE
				MOUSE_DEVICE=$X_MOUSE2
			else
				CONFIGFILE=$X_PATH/lib/X11/XF86Config-Xorg_Head1.tpl
				CONFIGSERVER=$CONFIGFILE
				MOUSE_DEVICE=$X_MOUSE1
			fi
		else
			CONFIGFILE=$X_PATH/lib/X11/XF86Config-Xorg_Dual.tpl
			CONFIGSERVER=$X_AUTO
		fi
	else
		CONFIGFILE=$X_PATH/lib/X11/XF86Config-Xorg_Dual.tpl
		CONFIGSERVER=$X_AUTO
	fi
    	if [ -n "$VNC_PATH" ] ; then 
		awk "/Section \"ServerLayout\"/,/EndSection/" $CONFIGSERVER | \
         	  awk '{print $0; if ( /Identifier/ ) system("cat '$VNC_PATH/vnc_input.tpl'")}' >> $X_CONFIG
		cat $VNC_PATH/vnc_keyboard.tpl >> $X_CONFIG
	else
		awk "/Section \"ServerLayout\"/,/EndSection/" $CONFIGSERVER >> $X_CONFIG
	fi

	awk "/Section \"Module\"/,/EndSection/" $CONFIGSERVER >> $X_CONFIG
    
	echo s\@\$MOUSE_PROTOCOL@$MOUSE_PROTOCOL@g >> /tmp/script$DISPLAY_NUMBER
   	echo s\@\$MOUSE_DEVICE@$MOUSE_DEVICE@g >> /tmp/script$DISPLAY_NUMBER
  	echo s\@\$MOUSE_RESOLUTION@$MOUSE_RESOLUTION@g >> /tmp/script$DISPLAY_NUMBER
  	echo s\@\$MOUSE_SENSITIVITY@$MOUSE_SENSITIVITY@g >> /tmp/script$DISPLAY_NUMBER
        echo s\@\$KEYBOARD_DEVICE@$KEYBOARD_DEVICE@g >> /tmp/script$DISPLAY_NUMBER
 	echo s/\$DISPLAY_NUMBER/$DISPLAY_NUMBER/g >> /tmp/script$DISPLAY_NUMBER
	cat $CONFIGFILE | sed -f /tmp/script$DISPLAY_NUMBER | awk "/Section \"InputDevice\"/,/EndSection/"  >> $X_CONFIG

	rm /tmp/script$DISPLAY_NUMBER
	rm $X_OPTIONS
	return 0;
    else
	echo -e "\n\nError, Configuration for Xorg has failed!!!!!" >> $LOGFILE
	echo "Check /var/log/x.config.log for details" >> $LOGFILE
	sleep 2
	echo -e "\nTail of log file is:" >> $LOGFILE
	tail /var/log/x.config.log >> $LOGFILE
	echo -e "\n" >> $LOGFILE
	sleep 2
	return 1;
    fi
}

build_config()
{
    X_CONFIG=/etc/X11/XF86Config-$DISPLAY_NUMBER

    if [ ! -e $X_CONFIG ] ; then
	    # Automagically detect what X server to use
	    if pkg_is_executable Xorg && parse_xconfig Xorg && xorg_autoconfig ;  then
	       X_SERVER=Xorg
	    elif pkg_is_executable XF86_S3 && parse_xconfig XF86_S3 \
		    && ! XF86_S3 -probeonly 2>&1 | \
		    grep "None of the configured devices"; then
		X_SERVER=XF86_S3
	    elif pkg_is_executable XF86_SVGA && parse_xconfig XF86_SVGA \
		    && ! XF86_SVGA -probeonly 2>&1 | \
		    grep "None of the configured devices"; then
		X_SERVER=XF86_SVGA
	    elif pkg_is_executable Xvesa; then
		X_SERVER=Xvesa
	    else
		"Can't autodetect your video card!!! Do you have one? ;)"
		sleep 2
	    fi
	    echo "X_SERVER=$X_SERVER" >> $TS_RUNTIME
    fi
}

case "$1" in  
init)
  if ! pkg_initialized $PACKAGE; then
    
    if pkg_is_loaded mdetect && ! pkg_initialized mdetect; then
       pkg init mdetect
       . $TS_GLOBAL
    fi

    pkg_set_init_flag $PACKAGE
  fi
  ;;
start)
    if [ ! -e /tmp/.X11-unix/X$DISPLAY_NUMBER ]; then
	echo "Starting $0 server" >> $LOGFILE

	if [ -n "$X_COOKIE" ] ; then
		xauth -f $XAUTHHOME/.Xauthority add :$DISPLAY_NUMBER.0 - $X_COOKIE >> $LOGFILE 2>&1
    	fi

	if  [ -e /bin/mkfontdir ] ; then
		if [ -e /usr/X11R6/lib/X11/fonts/75dpi ] ; then
			mkfontdir /usr/X11R6/lib/X11/fonts/75dpi
		fi
	fi

	build_config
	if [ -n "$X_SERVER" ]; then
  	  build_command
	  # Delay needed for dual head support
  	  if [ "$X_SERVER" = "Xorg" ] && [ "$POSITION" -ge 2 ] ; then
		sleep 6
	  fi
	  X_CMD="$X_CMD -nolisten tcp"
	  echo $X_CMD >> $LOGFILE
	  $X_CMD >> $LOGFILE 2>&1 &
	  sleep 1

	  if [ -n "$MOUSE_ACCELERATION" ]; then 
	  	echo xset -display :$DISPLAY_NUMBER m ${MOUSE_ACCELERATION} 1 >> $LOGFILE
	  	xset -display :$DISPLAY_NUMBER m ${MOUSE_ACCELERATION} 1 >> $LOGFILE 2>&1 &
	  fi

	  if [ "$X_SERVER" = "Xvesa" ]; then
	      if [ ! /tmp/.X11-unix ]; then
	        mkdir /tmp/.X11-unix
              fi
	      touch /tmp/.X11-unix/X$DISPLAY_NUMBER
	  fi
	else
	  echo "XSERVER variable is not defined, error!!!"
	  echo "X aborted, starting shell instead."
	  ash
	fi
    fi
    ;;
console|menu)
    if [ ! -e /tmp/.X11-unix/X$DISPLAY_NUMBER ]; then
	echo "Starting $0 server" >> $LOGFILE

	if [ -n "$X_COOKIE" ] ; then
		xauth -f $XAUTHHOME/.Xauthority add :$DISPLAY_NUMBER.0 - $X_COOKIE >> $LOGFILE 2>&1
    	fi

	build_config
	if [ -n "$X_SERVER" ]; then
	  build_command
	  if [ "$2" = "" ] ; then
		  X_CMD="$X_CMD -broadcast"
	  elif [ "$3" = "" ] ; then
		  X_CMD="$X_CMD -query $2"
	  else
	 	 X_CMD="$X_CMD $3 $2" 
	  fi

	  echo $X_CMD >> $LOGFILE
	  exec $X_CMD >> $LOGFILE 2>&1
	  if [ $X_SERVER = "Xvesa" ]; then
	      if [ ! /tmp/.X11-unix ]; then
	        mkdir /tmp/.X11-unix
              fi
	      touch /tmp/.X11-unix/X$DISPLAY_NUMBER
	  fi

 	else
	  echo "XSERVER variable is not defined, error!!!"
	  echo "X aborted, starting shell instead."
	  ash
	fi
    fi
    ;;
help)
    echo "Usage: $0 {init|start|stop|console|menu}"
    ;;
*)
    exit 1
    ;;
esac

exit 0
