#! /bin/sh

set -e

for program in /usr/X11R6/bin/xdm /usr/X11R6/bin/xfs
do
  if [ -x $program ]
  then
    start-stop-daemon --stop --quiet --oknodo --exec $program
  fi
done

# remove old symbolic links used for choosing the X server
if [ -L /usr/X11R6/bin/X ]
then
  rm -f /usr/X11R6/bin/X
fi
if [ -L /etc/X11/X ]
then
  rm -f /etc/X11/X
fi

if [ -f /etc/X11/xdm/Xstartup_0 -a ! -e /etc/X11/xdm/Xstartup ]
then
  mv /etc/X11/xdm/Xstartup_0 /etc/X11/xdm/Xstartup
fi

if [ -e /usr/bin/X11 -a ! -L /usr/bin/X11 ]
then
  echo "Warning: /usr/bin/X11 was not a symlink. It has been moved to"
  echo "/usr/bin/X11.old"
  mv /usr/bin/X11 /usr/bin/X11.old
fi

if [ -e /usr/lib/X11 -a ! -L /usr/lib/X11 ]
then
  echo "Warning: /usr/lib/X11 was not a symlink. It has been moved to"
  echo "/usr/lib/X11.old"
  mv /usr/lib/X11 /usr/lib/X11.old
fi

# if we're upgrading from xbase <3.1.2-8 offer to save the configuration
if [ "$1" = "install" -o "$1" = "upgrade" ]
then
  # we might have to do something special to cope with pre-ELF X setups
  if [ -n "$2" ]
  then
    if [ ! -e /etc/X11/config ]
    then
      # if the user has previously asked to run xdm, save this info
      # and change it back to run_xdm=0
      if [ -e /etc/init.d/xdm ]
      then
	if grep -q ^run_xdm=1 /etc/init.d/xdm
	then
	  echo start-xdm >>/etc/X11/config.instnotes
	  sed s/run_xdm=1/run_xdm=0/ /etc/init.d/xdm >/tmp/xdm.$$
	  mv /tmp/xdm.$$ /etc/init.d/xdm && chmod 755 /etc/init.d/xdm
	fi
      fi
      # likewise for xfs
      if [ -e /etc/init.d/xfs ]
      then
	if grep -q ^run_xfs=1 /etc/init.d/xfs
	then
	  echo start-xfs >>/etc/X11/config.instnotes
	  sed s/run_xfs=1/run_xfs=0/ /etc/init.d/xfs >/tmp/xfs.$$
	  mv /tmp/xfs.$$ /etc/init.d/xfs && chmod 755 /etc/init.d/xfs
	fi
      fi
      # ask the user whether they want to save their conffiles
      echo "The version of the Debian xbase package that you are installing"
      echo "has many new configuration files. Would you like to save a copy"
      echo -n "of your old configuration files? [yn] "
      read
      if [ "$REPLY" = "n" -o "$REPLY" = "N" ]
      then
	echo "No copy of the configuration files has been saved. You will"
	echo "be asked whether you want to keep the old versions of the"
	echo "configuration files or install the new ones later on in this"
	echo "installation. This question will be asked for each separate"
	echo "file. Please make sure that you answer the same way for all"
	echo "the files; if you try to mix old and new configuration files"
	echo "it is likely not to work."
      else
	# copy the xdm configuration files
	if [ -e /etc/X11/xdm ]
	then
	  cp -R /etc/X11/xdm /etc/X11/xdm.old
	  echo "Your old xdm configuration is now in /etc/X11/xdm.old"
	fi
	# move the Xsession file
	if [ -x /etc/X11/Xsession ]
	then
	  cp /etc/X11/Xsession /etc/X11/Xsession.old
	  echo "Your old Xsession is now in /etc/X11/Xsession.old"
	fi
      fi
    fi
  fi
fi

exit 0
