#!/usr/bin/env bash
#
# Copyright (c) 2007-2010 VMware, Inc.  All rights reserved.
#

# Must come before set -e.
thisDir="$(dirname $0)"
. "$thisDir"/functions

set -e

[ $# -ne 1 ] && error "Incorrect number of arguments provided"

command=$1
PACKAGE=$(basename $(dirname $0))
MODULE=

xConfig="/etc/X11/xorg.conf"
xConfigMustExist=yes

ensure_xconfig_exists()
{
   # If X's configuration file doesn't exist, and it's not an autoconfig
   # system, we have to create one so we can then modify the configuration.
   if [ ! -e "$xConfig" -a "$xConfigMustExist" != no ]; then
      install -m 600 "$thisDir"/XF86Config-4 "$xConfig"

      # Fix the mouse device so it points at the correct device file.
      # Logic copied from tar-tools' config.pl.
      # XXX: Ideally, we'd hardcode just the right path, since we have
      # knowledge of the specific system we're targetting. However,
      # there wasn't time for that.
      if [ -e /dev/mouse ]; then
         mouseDevice=
      elif [ -e /dev/input/mice ]; then
         mouseDevice=/dev/input/mice
      elif [ -e /dev/psaux ]; then
         mouseDevice=/dev/psaux
      fi

      if [ -n "$mouseDevice" ]; then
         replace \
            "s,^\(\s*Option\s\+\"Device\"\s\+\).*\$,\\1\"$mouseDevice\"," \
            "$xConfig"
      fi
   fi
}

# Substitutes any Driver field that has the name $from with $to while
# preserving whitespace.
replace_driver()
{
   local from="$1"
   shift
   local to="$1"
   shift

   # If the config ought to exist, it does, thanks to ensure_xconfig_exists, so
   # don't throw errors if it doesn't.
   if [ -e "$xConfig" ]; then
      replace "s,Driver\(\s\+\)\"$from\",Driver\1\"$to\",g" "$xConfig"
   fi
}

configure_mouse()
{
   replace_driver mouse vmmouse
}

configure_display()
{
   replace_driver vesa vmware
}

deconfigure_mouse()
{
   replace_driver vmmouse mouse
}

deconfigure_display()
{
   replace_driver vmware vesa
}

if is_rhel && [ `get_rhel_major_version` -eq 5 ]; then
   configure_mouse()
   {
      python $LIBDIR/install/$PACKAGE/x-conf-rhel.py install vmmouse
   }

   configure_display()
   {
      python $LIBDIR/install/$PACKAGE/x-conf-rhel.py install vmware
   }

   deconfigure_mouse()
   {
      python $LIBDIR/install/$PACKAGE/x-conf-rhel.py uninstall vmmouse
   }

   deconfigure_display()
   {
      python $LIBDIR/install/$PACKAGE/x-conf-rhel.py uninstall vmware
   }
fi

case $PACKAGE in
   vmware-open-vm-tools-*-drv-display)
      MODULE=display
      ;;
   vmware-open-vm-tools-*-drv-mouse)
      MODULE=mouse
      ;;
   *)
      error "Unknown package $PACKAGE"
      ;;
esac

case "$command" in
   install)
      ensure_xconfig_exists
      configure_$MODULE
      ;;
   upgrade)
      ;;
   uninstall)
      deconfigure_$MODULE
      ;;
   *)
      echo "Unknown option $1" >&2
      ;;
esac
