#!/bin/sh
#
### BEGIN INIT INFO
# Provides:          fliwi-vmware-support
# Required-Start:    $local_fs $remote_fs $fliwi
# Required-Stop:
# Should-Start:
# Should-Stop:
# X-Start-Before:    fliwi-install-configured-packages
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: Support for vmware virtual servers
# Description:       This cares about installin open-vm-tools on
#                    vmware virtual servers
### END INIT INFO

NAME=fliwi-install-configured-packages

. /lib/lsb/init-functions

ymc_check_if_open_vm_tools_are_installed()
{
  if [ $(dpkg --get-selections | grep -c -E -e '^open-vm-modules-'$(uname -r)'[[:space:]]+install$') -eq 0 ] || \
     [ $(dpkg --get-selections | grep -c -E -e '^open-vm-tools[[:space:]]+install$') -eq 0 ] ; then
    echo "WARNING: open-vm-tools are not (fully) installed" 1>&2
    echo 0
    return 1
  else
    echo "OKAY: open-vm-tools are installed" 1>&2
    echo 1
    return 0
  fi
}

ymc_install_open_vm_tools()
{
  DEBIAN_FRONTEND=noninteractive apt-get --assume-yes install module-assistant
  /usr/bin/module-assistant --non-inter prepare
  /usr/bin/module-assistant --non-inter auto-install open-vm-source
  DEBIAN_FRONTEND=noninteractive apt-get --assume-yes install open-vm-tools
  /etc/init.d/open-vm-tools restart
}

ymc_check_if_open_vm_tools_are_uninstalled()
{
  if [ $(dpkg --get-selections 'open-vm-*' | sed -r 's/[[:space:]].*//' | wc -l) -ne 0 ]; then
    echo "WARNING: open-vm-tools are (partly) installed" 1>&2
    echo 0
    return 1
  else
    echo "OKAY: open-vm-tools are not installed" 1>&2
    echo 1
    return 0
  fi
}

ymc_uninstall_open_vm_tools()
{
  dpkg --purge $(dpkg --get-selections 'open-vm-*' | sed -r 's/[[:space:]].*//')
}

case "$1" in
  start|restart)
    if [ -x "/usr/sbin/dmidecode" ]; then
      if [ $(/usr/sbin/dmidecode -s system-manufacturer | grep -c VMware) -eq 1 ]; then
        echo "This seems to be a VMware virtual server..." 1>&2
        if [ $(ymc_check_if_open_vm_tools_are_installed) -eq 0 ]; then
          ymc_install_open_vm_tools
        fi
      else
        echo "This seems not to be a VMware virtual server..." 1>&2
        if [ $(ymc_check_if_open_vm_tools_are_uninstalled) -eq 0 ]; then
          ymc_uninstall_open_vm_tools
        fi
      fi
    fi
  ;;

  stop)
  ;;

  reload|force-reload|force-stop|status)
    echo "Error: argument '$1' not supported" >&2
    exit 3
  ;;

  *)
    echo "Usage: /etc/init.d/$NAME {start|restart}"
    exit 3
  ;;
esac

exit 0
