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

set -e

trap "" USR1 # Used for canceling installation, ignore.

ETCDIR=/etc/vmware-installer-horizon

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
}

# 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

# vmis-launcher requires glibc versioin >= MIN_GLIBC_VERSION
validate_glibc_version

export VMWARE_USE_SYSTEM_LIBS=yes
PYTHON_VERSION=`python -V 2>&1 | awk  '{print $2}'`
if [[ ${PYTHON_VERSION:0:1} -eq '3' ]] ;then
   ln -fs "$VMWARE_INSTALLER"/vmis-py3 "$VMWARE_INSTALLER"/vmis
   rm -rf "$VMWARE_INSTALLER"/vmis-py2
   ln -fs "$VMWARE_INSTALLER"/vmis-py3 "$VMWARE_INSTALLER"/vmis-py2
else
   ln -fs "$VMWARE_INSTALLER"/vmis-py2 "$VMWARE_INSTALLER"/vmis
   rm -rf "$VMWARE_INSTALLER"/vmis-py3
   ln -fs "$VMWARE_INSTALLER"/vmis-py2 "$VMWARE_INSTALLER"/vmis-py3
fi

# export INSTALL_ARCH variable
# It is used to be exported in vmware-installer-launcher which is replaced with
# local python now. So we should export it manually before start python.
arch=`uname -m`
if [ "$arch" == 'x86_64' ] ;then
   export INSTALL_ARCH=x64
else
   export INSTALL_ARCH=x86
fi

VMWARE_INSTALLER="$VMWARE_INSTALLER" VMISPYVERSION="$VMISPYVERSION" python -W ignore::DeprecationWarning "$VMWARE_INSTALLER"/vmware-installer.py "$@"
