#!/bin/bash
#
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2008, 2009, 2010, 2012, 2013, 2014, 2015, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
#; ***** END LICENSE BLOCK *****
# 

if [ x`whoami` != xzimbra ]; then
    echo Error: must be run as zimbra user
    exit 1
fi

zimbra_java_home=/opt/zimbra/common/lib/jvm/java
jspc_src_dir=/opt/zimbra/mailboxd/webapps/zimbra
jspc_build_dir=/opt/zimbra/mailboxd/work/zimbra/jsp
jspc_class_path="/opt/zimbra/lib/jars/*:/opt/zimbra/common/jetty_home/lib/*:/opt/zimbra/common/jetty_home/lib/apache-jsp/*:/opt/zimbra/common/jetty_home/lib/apache-jstl/*:/opt/zimbra/lib/jars/*:/opt/zimbra/jetty/lib/ext/*:/opt/zimbra/jetty/lib/plus/*:/opt/zimbra/jetty/lib/naming/*:/opt/zimbra/lib/ext/*:/opt/zimbra/jetty/common/lib/*:/opt/zimbra/jetty/webapps/zimbra/WEB-INF/lib/*"

extensions="backup clamscanner network zimbra-license zimbrahsm zimbrasync"
ext_dir="/opt/zimbra/lib/ext-common"
for i in $extensions; do
  if [ -d "/opt/zimbra/lib/ext/$i" ]; then
   jspc_class_path="${jspc_class_path}:${ext_dir}/$i"
  fi
done

for i in `ls /opt/zimbra/common/jetty_home/lib/apache-jsp/*.jar`; do
  if [ x"$class_path" = "x" ]; then
    class_path="$i"
  else
    class_path="${class_path}:$i"
  fi
done

for i in `ls /opt/zimbra/common/jetty_home/lib/apache-jstl/*.jar`; do
  if [ x"$class_path" = "x" ]; then
    class_path="$i"
  else
    class_path="${class_path}:$i"
  fi
done

java_version=$(${zimbra_java_home}/bin/java -version 2>&1 | grep "java version" | sed -e 's/"//g' | awk '{print $NF}' | awk -F_ '{print $1}')
if [ x"$java_version" = "x1.6.0" ]; then
  java_options="-XX:ErrorFile=/opt/zimbra/log"
else
  java_options=""
fi

java_cmd="${zimbra_java_home}/bin/java $java_options \
  -client -Xmx256m \
  -Dzimbra.home=/opt/zimbra \
  -Djava.library.path=/opt/zimbra/lib \
  -classpath ${jspc_class_path}:${class_path}"

if [ -d "${jspc_build_dir}" ]; then
  rm -rf ${jspc_build_dir}
fi
mkdir ${jspc_build_dir}

compile_jsp() {
  ${java_cmd} org.apache.jasper.JspC -v -trimSpaces -d ${jspc_build_dir} -webapp ${jspc_src_dir} -uriroot ${jspc_src_dir} -compile
  return $?
}

compile_jsp
if [ $? = 0 ]; then
  echo "done."
else
  echo "failed."
fi
