#!/usr/bin/env bash
#
# VMware Installer Service command line interface.
#


###############################################################
#
# init_gtk_environment
#     Init GTK environment.
#
###############################################################

init_gtk_environment() {
   # GDK_PIXBUF_MODULE_FILE
   if [ -n "${GDK_PIXBUF_MODULE_FILE}" ]; then
      unset GDK_PIXBUF_MODULE_FILE
   fi
   if [ -n "${VMWARE_GDK_PIXBUF_MODULE_FILE}" ]; then
      unset VMWARE_GDK_PIXBUF_MODULE_FILE
   fi

   # GTK_PATH
   if [ -n "${GTK_PATH}" ]; then
      unset GTK_PATH
   fi
   if [ -n "${VMWARE_GTK_PATH}" ]; then
      unset VMWARE_GTK_PATH
   fi

   # GIO_MODULE_DIR
   if [ -n "${GIO_MODULE_DIR}" ]; then
      unset GIO_MODULE_DIR
   fi
   if [ -n "${VMWARE_GIO_MODULE_DIR}" ]; then
      unset VMWARE_GIO_MODULE_DIR
   fi

   # GTK_EXE_PREFIX
   if [ -n "${GTK_EXE_PREFIX}" ]; then
      unset GTK_EXE_PREFIX
   fi
   if [ -n "${VMWARE_GTK_EXE_PREFIX}" ]; then
      unset VMWARE_GTK_EXE_PREFIX
   fi

   # GTK_IM_MODULE
   if [ -n "${GTK_IM_MODULE}" ]; then
      unset GTK_IM_MODULE
   fi

   # GTK3_MODULES
   if [ -n "${GTK3_MODULES}" ]; then
      unset GTK3_MODULES
   fi

   # GSETTINGS_SCHEMA_DIR
   if [ -n "${GSETTINGS_SCHEMA_DIR}" ]; then
      unset GSETTINGS_SCHEMA_DIR
   fi
   if [ -n "${VMWARE_GSETTINGS_SCHEMA_DIR}" ]; then
      unset VMWARE_GSETTINGS_SCHEMA_DIR
   fi

   # Unset luiloader's caching libraries path.
   if [ -n "${VM_LUILOADER_LDPATH_CACHE}" ]; then
      unset VM_LUILOADER_LDPATH_CACHE
   fi
}


###############################################################
#
# need_uninstall_privious(product, comparedVMISVer)
#
# Result:
# 0 only if 1) In the GUI session, "DISPLAY" is set.
#           2) The product is correctly installed.
#           3) The installed vmis is less than vmis version provided.
# 1 for the status which cannot satisfy the condition.
#
##############################################################

need_uninstall_privious() {
   typeset product=$1
   typeset comparedVer=$2
   typeset bootstrap_env="${VMWARE_BOOTSTRAP}"
   typeset use_gui_first_env="${USE_GUI_FIRST}"
   typeset installer="/usr/bin/vmware-installer"

   if [ -z "${DISPLAY}" ]; then
      return 1
   fi

   if [ ! -e "${installer}" ]; then
      # No installer softlink.
      return 1
   fi

   if [ -z "$(readlink ${installer} 2>/dev/null)" ]; then
      # No installer binary, possible direct directory removal?
      return 1
   fi


   # When use offfical installer, use official environment
   # variable "VMWARE_BOOTSTRAP" and no GUI.
   unset VMWARE_BOOTSTRAP
   unset USE_GUI_FIRST
   unset VMWARE_PRODUCT_NAME

   ${installer} -l 2>/dev/null | grep -q "${product}" 2>/dev/null
   if [ "$?" != "0" ]; then
      # There is no VMRC installed.
      if [ -n "${bootstrap_env}" ]; then
         export VMWARE_BOOTSTRAP=${bootstrap_env}
      fi
      if [ -n "${use_gui_first_env}" ]; then
         export USE_GUI_FIRST=${use_gui_first_env}
      fi
      return 1
   fi

   typeset vmisVersionStr=$(${installer} --version 2>/dev/null)
   if [ -z "${vmisVersionStr}" ]; then
      # Cannot detect installedvmis version.
      if [ -n "${bootstrap_env}" ]; then
         export VMWARE_BOOTSTRAP=${bootstrap_env}
      fi
      if [ -n "${use_gui_first_env}" ]; then
         export USE_GUI_FIRST=${use_gui_first_env}
      fi
      return 1
   fi

   typeset installedVer=$(echo "${vmisVersionStr}" | sed -e "s/\.//g" 2>/dev/null)
   if [ -n "${installedVer}" ] && [ "${installedVer}" -lt "${comparedVer}" ]; then
      if [ -n "${bootstrap_env}" ]; then
         export VMWARE_BOOTSTRAP=${bootstrap_env}
      fi
      if [ -n "${use_gui_first_env}" ]; then
         export USE_GUI_FIRST=${use_gui_first_env}
      fi
      return 0
   fi

   if [ -n "${bootstrap_env}" ]; then
      export VMWARE_BOOTSTRAP=${bootstrap_env}
   fi
   if [ -n "${use_gui_first_env}" ]; then
      export USE_GUI_FIRST=${use_gui_first_env}
   fi
   return 1
}


set -e

setsi="no"
username="${VMWARE_GKSU_USER}"

if [ -z "${username}" ] && [ -n "${SUDO_USER}" ]; then
   username=${SUDO_USER}
fi

exit_install() {
   if [ "${setsi}" = "yes" ] && [ -n "${username}" ]; then
      # When the setsi is "yes", we must be root/sudo account
      # and set the "SI:localuser:root" by us.
      su ${username} -c "xhost -SI:localuser:root" >/dev/null 2>&1
   fi
}

# Used for canceling installation, rollback possible xhost setting.
trap "exit_install" USR1 EXIT INT QUIT TERM

ETCDIR=/etc/vmware-installer

MIN_GLIBC_VERSION=2.5


# Check to make sure glibc version >= MIN_GLIBC_VERSION, meet the minimum
# glibc version requirement to launch vmis-launcher. Function returns with
# no side effect if version check succeeds, exits with 1 if version check
# fails, but only emits a warning if the version cannot be determined.
validate_glibc_version() {
   # Example ldd output:
   #   ubuntu:
   #      ldd (Ubuntu EGLIBC 2.12.1-0ubuntu10.2) 2.12.1
   #      ...
   #   other linux distributions:
   #      ldd (GNU libc) 2.12
   #      ...
   read glibcMajor glibcMinor <<<`ldd --version | awk '/^ldd/ { split($NF,v,/\./); print v[1],v[2]; }'`
   if [ "$glibcMinor" == "" ]; then
      echo "Warning: VMware Installer could not determine this system's glibc version."
      return
   fi

   # Make sure glibc version >= MIN_GLIBC_VERSION
   minVersion=$(expr `echo $MIN_GLIBC_VERSION | awk -F. '{print $1*65536+$2}'`)
   glibcVersion=$(expr $glibcMajor \* 65536 + $glibcMinor)

   if [ $glibcVersion -lt $minVersion ]; then
      echo "Error: This system's glibc (version $glibcMajor.$glibcMinor) is too old. This product requires glibc version $MIN_GLIBC_VERSION or later."
      exit 1
   fi
}

installJob="no"
uninstallJob="no"
silent="no"
product_name=""
need_product="no"

for arg in "$@"
do
   if [[ "$arg" =~ ^--install.* ]] || [ "$arg" == "-i" ]; then
      installJob="yes"
      continue
   fi

   if [[ "$arg" =~ ^--co.* ]]; then
      # Currently there is only "--custom" and "--console"
      # So assume to be console mode, and let vmware-installer.py
      # to detect the "option" input error.
      silent="yes"
      continue
   fi

   if [[ "$arg" =~ ^--uninstall-.* ]]; then
      uninstallJob="yes"
      set +e
      product_name=$(echo "${arg}" | awk -F'=' '{ print $2 }' 2>/dev/null)
      set -e
      if [ -z "${product_name}" ]; then
         need_product="yes"
      fi
      continue
   fi

   if [ "$arg" == "-u" ]; then
      uninstallJob="yes"
      need_product="yes"
      continue
   fi

   if [ "${need_product}" == "yes" ]; then
      product_name=$arg
      need_product="no"
      continue
   fi
done

if [[ -z "${product_name}" ]] && [[ -n "${VMWARE_PRODUCT_NAME}" ]]; then
   # Try to get the environment variable "VMWARE_PRODUCT_NAME",
   # in the installation scenario, this is exported by the
   # bundle script.
   product_name="${VMWARE_PRODUCT_NAME}"
   unset VMWARE_PRODUCT_NAME
fi

set +e
if [ "${product_name}" == "vmware-vmrc" ] && [ -n "${DISPLAY}" ]; then
   typeset bootstrap_env="${VMWARE_BOOTSTRAP}"
   if [ "${uninstallJob}" == "yes" ] && [ "${silent}" == "no" ]; then
      typeset installer="/usr/bin/vmware-installer"
      if [ -n "${bootstrap_env}" ]; then
         unset VMWARE_BOOTSTRAP
      fi
      ${installer} -l | grep -q "${product_name}" 2>/dev/null
      if [ "$?" == "0" ]; then
         # Only the uninstalling product is currently installed.
         # set the environment "USE_GUI_FIRST" to be "yes".
         export USE_GUI_FIRST="yes"
         # Always use shipped libraries.
         unset VMWARE_USE_SYSTEM_LIBS
         export VMWARE_USE_SHIPPED_LIBS=1
      fi
      if [ -n "${bootstrap_env}" ]; then
         export VMWARE_BOOTSTRAP=${bootstrap_env}
      fi
   else
      if [ "${installJob}" == "yes" ] && [ "${silent}" == "no" ]; then
         export USE_GUI_FIRST="yes"
         init_gtk_environment
         need_uninstall_privious ${product_name} "300"
         if [ "$?" == "0" ]; then
            # Legacy vmis version and VMRC installed,
            # Uninstall the previous version VMRC.
            if [ -n "${bootstrap_env}" ]; then
               unset VMWARE_BOOTSTRAP
            fi
            /usr/bin/vmware-installer -u ${product_name} 2>/dev/null
            typeset result=$?
            if [ "${result}" == "0" ]; then
               # Previous VMRC has been removed,
               # Re-launch new version VMRC installer.
               if [ -n "${bootstrap_env}" ]; then
                  export VMWARE_BOOTSTRAP=${bootstrap_env}
               fi
               export VMWARE_PRODUCT_NAME=${product_name}
               exec $0 "$@"
            else
               # Let us return same error as uninstall/removal.
               exit ${result}
            fi
         fi
         # Always use shipped libraries.
         unset VMWARE_USE_SYSTEM_LIBS
         export VMWARE_USE_SHIPPED_LIBS=1
      fi
   fi
fi
set -e

# VMWARE_BOOTSTRAP is overriden in the bootstrapper so that it can be
# sourced from a temporary location during installation.
if [ -e "$VMWARE_BOOTSTRAP" ]; then
   . "$VMWARE_BOOTSTRAP"
else
   . $ETCDIR/bootstrap
fi

. "$VMWARE_INSTALLER"/python/init.sh

# vmis-launcher requires glibc versioin >= MIN_GLIBC_VERSION
validate_glibc_version

# set "set +e" to make sure "| grep" can work in our scenario.
set +e
if [ -n "${DISPLAY}" ]; then
   ps -e | grep -q -i "Xwayland" >/dev/null 2>&1
   if [ "$?" = "0" ]; then
      # we only do this for Xwayland session
      account=`id -unr`
      if [ "${account}" = "root" ] && [ -n "${username}" ] && \
         [ "${username}" != "${account}" ]; then
         # we only do this when the user realname is not "root"
         # and we can only switch to realname user to do the xhost setting
         # in wayland session
         su ${username} -c "xhost" 2>&1 | grep -q 'SI:localuser:root' >/dev/null 2>&1
         if [ "$?" != "0" ]; then
            # we only do this for "root" entry is not enabled.
            su ${username} -c "xhost SI:localuser:root" >/dev/null 2>&1
            if [ "$?" = "0" ]; then
               setsi="yes"
            fi
         fi
      fi
   fi
fi
# rollback to "set -e" environment.
set -e

cdsHelper=''
if [ -n "$VM_GKSU_MESSAGE" ]; then
   if [ "$PRODUCT_NAME" == "vmware-workstation" ] || [ "$PRODUCT_NAME" == "vmware-player" ]; then
      cdsHelper="$VMWARE_INSTALLER"/vmware-cds-helper
   fi
fi

if [ "$cdsHelper" != "" ] && [ "$installJob" == "yes" ] && [ "$silent" != "yes" ]; then
   LC_ALL="C" VMWARE_INSTALLER="$VMWARE_INSTALLER" VMISPYVERSION="$VMISPYVERSION" PRODUCT_NAME="$PRODUCT_NAME" "$cdsHelper" "$VMWARE_INSTALLER"/vmis-launcher "$VMWARE_INSTALLER"/vmware-installer.py "$@"
else
   LC_ALL="C" VMWARE_INSTALLER="$VMWARE_INSTALLER" VMISPYVERSION="$VMISPYVERSION" "$VMWARE_INSTALLER"/vmis-launcher "$VMWARE_INSTALLER"/vmware-installer.py "$@"
fi
exit_code=$?

# Remove xhost settings configured by us.
exit_install
exit ${exit_code}
