#!/bin/sh

# * backup system xorg.conf to $backup
# * create new xorg.conf
# * run X-server with alterator-x11 interface
#   on Apply button alterator-x11 deletes our $backup
# * if $backup was not deleted -- replace system xorg.conf by it

flag="/tmp/alterator/config-x11"
backup="/tmp/alterator/config-x11.backup"
XORG_CONF="/etc/X11/xorg.conf"
PATH=/usr/lib/alterator-x11:"$PATH"

exit_handler() {
  local rc=$?
  trap - EXIT
  rm -rf -- "$flag"
  [ -f "$backup" ] && mv -f "$backup" "$XORG_CONF"
  exit $rc
}

if [ -f "/tmp/.X0-lock" ]; then
  echo "Server is already active for display 0"
  echo "        If this server is no longer running, remove /tmp/.X0-lock"
  echo "        and start again."
  exit 1
fi

# We need alterator-standalone
if [ ! -x /usr/sbin/alterator-standalone ]; then
  echo "Can't find /usr/sbin/alterator-standalone"
  echo "Please install alterator-standalone package and try again."
  exit 1
fi

# We need hal and dbus.
# If there is no running daemons - let us try to start them
# note: if we start dbus we need to restart hal even if it is already running!
if [ "$(service messagebus status)" != "dbus-daemon is running" ]; then
  echo "This version of config-x11 needs dbus."
  echo "Let's try to start dbus daemon:"
  service messagebus start
  service haldaemon restart
  [ "$(service messagebus status)" = "dbus-daemon is running" ] || exit 1
fi

if [ "$(service haldaemon status)" != "hald is running" ]; then
  echo "This version of config-x11 needs hal."
  echo "Let's try to start hal daemon:"
  service haldaemon start
  [ "$(service haldaemon status)" = "hald is running" ] || exit 1
fi

# Message about synaptics driver
if ! rpm -q xorg-drv-synaptics > /dev/null; then
  dev="$(hal-find-by-property --key input.x11_driver --string synaptics)"
  if [ -n "$dev" ]; then
    echo "You may want to install xorg-drv-synaptics package"
    echo "for your device \"$(hal-get-property --udi $dev --key info.product)\""
    echo "Don't forget to restart haldaemon service after this."
  fi
fi


trap exit_handler HUP PIPE INT QUIT TERM EXIT
install -d "/tmp/alterator"
echo > "$flag"
cp -f "$XORG_CONF" "$backup"

x11_autosetup "$XORG_CONF"

other_drivers=$(video_scan -s drivers)

cmd="xinit /usr/sbin/alterator-standalone x11 -- -dpms -ac -dpi 80"
if ! $cmd &> /var/log/config-x11; then
  for drv in $other_drivers vga; do
    echo "Can't start Xorg server. Trying with driver $drv..."
    video_setup "$drv" "$XORG_CONF"
    $cmd &> /var/log/config-x11 && break || rc=$?
  done
fi
