#!/bin/bash
#
# ***** BEGIN LICENSE BLOCK *****
# Copyright (C) 2016 ZeXtras
#
# The contents of this file are subject to the ZeXtras License;
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.zextras.com/eula/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
# ***** END LICENSE BLOCK *****
#

OLD_JAVA_PATH="/opt/zimbra/java/bin/java"
NEW_JAVA_PATH="/opt/zimbra/common/lib/jvm/java/bin/java"

zal_path="/opt/zimbra/lib/ext/zextras/zal.jar"
zimbra_uid=$(id zimbra -u)
current_user=$(id -u)

if [[ -z ${zimbra_uid} || ${current_user} -ne ${zimbra_uid} ]]; then
  NONZIMBRA=1
else
  NONZIMBRA=0
fi

if [[ ! -e $zal_path ]]; then
  echo "ZeXtras Core not found.";
  exit 1;
fi
{
  [[ -t 0 && -t 1 && -n $TERM && $TERM != dumb ]] && which tput &> /dev/null && USE_TPUT=1
} || USE_TPUT=0

JAVA_PATH=${OLD_JAVA_PATH}
[ -e ${NEW_JAVA_PATH} ] && JAVA_PATH=${NEW_JAVA_PATH}

COMMAND="${JAVA_PATH} -Xmx128m -cp ${zal_path} org.openzal.zal.tools.ConsoleBoot com.zextras.zxcli.ZxSuiteCLI"

if [[ -z ${COLUMNS} ]]; then

  if [[ $USE_TPUT -eq 1 ]]; then

    COLUMNS=$(tput cols)

    if [[ $NONZIMBRA -eq 1 ]]; then
      sudo -u zimbra $COMMAND --columns ${COLUMNS} "$@"
    else
      eval $COMMAND --columns ${COLUMNS} '"$@"'
    fi

  else

    if [[ $NONZIMBRA -eq 1 ]]; then
      sudo -u zimbra $COMMAND "$@"
    else
      eval $COMMAND '"$@"'
    fi

  fi

else

  if [[ $NONZIMBRA -eq 1 ]]; then
    sudo -u zimbra $COMMAND --columns ${COLUMNS} "$@"
  else
    eval $COMMAND --columns ${COLUMNS} '"$@"'
  fi

fi
