#!/bin/sh
#
# Call xdebconfigurator and dexconf to set up the X config file.
#
# Do this after 75apt-get to make sure it happen after the XFree86
# package is installed and the debconf templates are loaded.
# Do this before 77Xhack, to make sure the HW detection tools are
# still installed.

set -e

# Run Xdebconfigurator to set values in the debconf-db.  Next it will
# run dexconf to write a new XF86Config-4 file.

xdebconf="/usr/sbin/xdebconfigurator"
dexconf="/usr/bin/dexconf"

if [ -x "$xdebconf" ]; then
    # run xdebconfigurator

    # First we find out which server package to use
    pkg=`xdebconfigurator 2>&1 |grep 'DEBIAN PACKAGE: '|awk '{print $3}'`

    # Only xserver-xfree86 is supported at the moment
    if [ xserver-xfree86 != "$pkg" ] ; then
	echo "error: Skipping xdebconfigurator.  Only xserver-xfree86 is supported."
	exit 1
     fi

     # Then we configure
     logger -p user.info -t xdebconfigurator \
	 "Generating new XFree86 config file."
     echo "info: Generating XFree86 config file using xdebconfigurator/dexconf."
     if $xdebconf -dcik; then
         # run dexconf, and keep going even if it fails.

	 # Make backup copy just in case
	 cfg="/etc/X11/XF86Config-4"
	 if [ -f $cfg ] ; then
	     timestamp=`date +%Y%m%d-%H%M`
	     cp $cfg $cfg-$timestamp
	 fi

         # an alternative to running dexconf would be to run
         # "dpkg-reconfigure xserver-xfree86" but in the end package
         # xserver-xfree86 will still use dexconf for writing the
         # file.
	 if $dexconf ; then
	     # update the md5sum to allow xserver-xfree86 reconfiguration
	     md5sum $cfg > /var/lib/xfree86/`basename $cfg`.md5sum
	     if diff -u $cfg-$timestamp $cfg > /dev/null ; then
		 # Files are identical, no need to keep the backup file.
		 rm $cfg-$timestamp
	     fi
	 else
	     echo "error: failed to run $dexconf."
	     exit 2
	 fi
     else
         echo "error: failed to run $xdebconf."
	 exit 3
     fi
fi

exit 0
