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

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

trap exit_handler HUP PIPE INT QUIT TERM EXIT
install -d "/tmp/alterator"

echo > "$flag"

if [ -f "$XORG_CONF" ]; then
	COMPAT_MODE=1
else
	XORG_CONF="/etc/X11/xorg.conf.d/10-monitor.conf"
fi
cp -f "$XORG_CONF" "$backup"

if [ -n "$COMPAT_MODE" ]; then
	x11_autosetup "$XORG_CONF"
fi

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..."
    if [ -n "$COMPAT_MODE" ]; then
        video_setup "$drv" "$XORG_CONF"
    else
        xsetup-monitor -d "$drv"
    fi
    $cmd &> /var/log/config-x11 && break || rc=$?
  done
fi
