#!/bin/bash
#
# Copyright 2017-2020,2022-2023 VMware, Inc.  All rights reserved.
#
# This script manages the VMware Horizon Client
#

libpath="/usr/lib/vmware"
binPath="/usr/lib/vmware/view"
html5mmrlibPath="$libpath/view/html5mmr"
usbdlibPath="$libpath/view/usb"
vdp_servicePath="/usr/lib/pcoip/vchan_plugins"
libtsdrClient="$libpath/view/vdpService/libtsdrClient.so"
snapPath="/snap/gnome-system-monitor/current/usr/lib/x86_64-linux-gnu"
pid_self=$$

# Set media provider install path base on $VMWARE_HORIZON_MEDIA_PROVIDER_PATH
if [[ "$VMWARE_HORIZON_MEDIA_PROVIDER_PATH" = "" ]]; then
    mediaproviderPath="/usr/lib/vmware/mediaprovider"
else
    mediaproviderPath="$VMWARE_HORIZON_MEDIA_PROVIDER_PATH"
fi

binFile="vmware-view"

# Get the executed user
user=
if [[ $USER = "" ]]; then
   if [ "`type -t 'whomai' 2>/dev/null`" = 'file' ]; then
      user=`whoami`
   fi
else
   user=$USER
fi

# Get the home path
homePath=
if [[ $HOME = "" ]]; then
   homePath="/home/$user"
else
   homePath=$HOME
fi


# Input argument from stdin
stdin_arg=

# Check the openssl libraires path we installed in /usr/lib/vmware
vm_ssl_path() {
   local sslPath
   if [ -d "$libpath" ]; then
      sslPath="$libpath"
   else
      sslPath=""
   fi
   echo "$sslPath"
}

# Add path to LD_LIBRARY_PATH
vm_append_to_library_path() {
   local ldBasePath
   if [ ! -z "$LD_LIBRARY_PATH" ]; then
      ldBasePath="$LD_LIBRARY_PATH"
   fi
   export LD_LIBRARY_PATH="$1:""$ldBasePath"
   # We use x11 lib in client, so cannot use wayland now
   export GDK_BACKEND=x11
}

# Function to export environment variable
vm_append_export() {
   local key=$1
   local val=$2

   export $key"=""$val"
}

# Export environment variable if libtsdrClient.so exists.
vm_folder_redirection_config() {
   if [ -x $libtsdrClient ]; then
      vm_append_export "ENABLE_FOLDER_REDIRECTION" "TRUE"
   fi
}


vm_run() {
   # Export openssl libraries path
   vm_append_to_library_path "$snapPath"
   vm_append_to_library_path "`vm_ssl_path`"
   vm_append_to_library_path "$vdp_servicePath"
   vm_append_to_library_path "$mediaproviderPath"
   vm_append_to_library_path "$usbdlibPath"
   vm_append_to_library_path "$html5mmrlibPath"
   vm_append_to_library_path "$libpath/view/lib"
   vm_append_to_library_path "$libpath"/gcc

   # Config tsdr feature
   vm_folder_redirection_config

   if [ -e "$binPath/bin/$binFile" ]; then
      if [ ! $stdin_arg ]; then
         "$binPath/bin/$binFile" "$@"
      else
         echo $stdin_arg | "$binPath/bin/$binFile" "$@"
      fi
   else
      echo "File not exists:/usr/lib/vmware/view/bin/$binFile"
      exit 1
   fi

   return "$?"
}


# Read stdin if it exists and there is "-p -" in command parameters
if [ ! -t 0 ] && [[ "$@" =~ "-p -" ]]; then
   read -t 1 stdin_arg
fi

# To execute the vmware-remotemks binary
export PATH="$binPath/client:$PATH"

vm_run "$@"
