#!/bin/sh -efu

# autodetect video hardware and create xorg.conf file
# - getting video driver from lspci, using table /usr/share/alterator-x11/videocards
#   fallback to fbdev, fallback to vesa
# - getting monitor parameters and resolution from ddc
# - setting some default resolution
# - setting all serial ports as mice
#   (other mouse types will be found by libXiconfig)

usage(){
cat <<EOF
  usage:
   x11_autosetup [-h] [-d <xdriver>] [-r <xres>]  [<file>]
  <xdriver> - video driver (default "auto")
  <xres>    - resolution (default "auto")
  <file>    - xorg.conf file for output (default /etc/X11/xorg.conf.auto)
EOF
> /dev/stderr
}

. shell-quote
. shell-error
. shell-getopt

PATH="/usr/lib/alterator-x11:$PATH"
xdriver=auto
xdriver_data=
xres=auto
xdepth=
monitor=

verbose=1

while getoptex "d: r: h" "$@"; do
  case "$OPTOPT" in
    "d") xdriver=$OPTARG ;;
    "r") xres=$OPTARG ;;
    "h") usage; exit ;;
    "--") break ;;
  esac
done

shift $(($OPTIND-1))

XORG_TEMPLATE="/usr/share/alterator-x11/xorg.conf"
XORG_CONF=${XORG_CONF:-${1:-}}
XORG_CONF=${XORG_CONF:-/etc/X11/xorg.conf.auto}

verbose "Creating new config file $XORG_CONF"
cp -f "$XORG_TEMPLATE" "$XORG_CONF"
if [ "$?" = 1 ]; then exit 1; fi

SETDRV="/usr/sbin/x11presetdrv"
verbose "Executing $SETDRV"
[ -x "$SETDRV" ] && "$SETDRV" ||:

# cleaning ddcdump cache file!
monitor_ddc clean ||:

##################################################
# setting up video driver

#try to setup driver only if xdriver options is set
if [ "$xdriver" != "auto" -a "$xdriver" != "" ]; then
  dtype="explicitly defined"
  video_setup "$xdriver" "$XORG_CONF"
  
  # finding xdepth
  xdepth="$(video_drv -s depth "$xdriver")"
  verbose "Using $dtype driver \"$xdriver\" with ${xdepth}bpp color depth"

  [ -z "$xdepth" ] || xconf -C "$xdepth" "$XORG_CONF" "$XORG_CONF"
fi

if [ "$xdriver" = "fbdev" ]; then
  xres="$(fbresolution)"
  if [ -n "$xres" ]; then
    verbose "  setting resolution $xres for \"fbdev\" driver"
  else
    verbose "  Error: can't get fbdev resolution!"
    xres=auto
  fi
fi

##################################################
# setting up monitor

monitor="$(monscan)"

verbose "Monitor \"$monitor\" found"

[ -z "$monitor" ] || monitor_setup "$monitor" "$XORG_CONF"

##################################################
# setting up resolution

# resolution is already set for fbdev!
if [ "$xres" = "auto" ]; then
  xres="$(monitor_ddc resbest)" ||:
  verbose "  resolution: $xres"
else
  verbose "Using explicitly defined resolution: $xres"
fi

[ -z "$xres" ] || resolution_setup "$xres" "$XORG_CONF"

##################################################
# setting up mouse

verbose "Setting up mice"
mouse_autosetup --xorg-conf "$XORG_CONF" xorg

##################################################
