#!/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"

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 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

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

x11_autosetup "$XORG_CONF"

cmd="xinit /usr/sbin/alterator-standalone x11 -- -dpms -ac -dpi 80"
if ! $cmd &> /var/log/config-x11; then
  for drv in vesa fbdev 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
