#!/bin/bash
# 
# ***** BEGIN LICENSE BLOCK *****
# 
# Portions created by Zimbra are Copyright (C) 2005, 2006 Zimbra, Inc.
# All Rights Reserved.
# 
# The Original Code is: Zimbra Network
# 
# ***** END LICENSE BLOCK *****
# 

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

source `dirname $0`/zmshutil || exit 1
zmsetvars \
	tomcat_pidfile \
	zimbra_home \
	zimbra_log_directory

pid=""	
if [ -s ${tomcat_pidfile} ]; then
    pid=`cat ${tomcat_pidfile}`
fi

isrunning() {
    kill -0 "$pid" 2> /dev/null
    return
}

opth=0
for opt in $@; do 
    if [ $opt = "-h" -o $opt = "--help" ]; then
        opth=1
        break
    fi
done

ropid=${zimbra_log_directory}/zmrestoreoffline.pid

if [ $opth -eq 0 ]; then
    if [ "$pid" != "" ]; then
        if isrunning; then
            echo "Error: tomcat still running (pid $pid)"
            exit 1
        fi
    fi
    if [ -s $ropid ]; then
        echo "Error: another instance of zmrestoreoffline (pid=`cat $ropid`) is already running"
        echo "       remove $ropid if this is not the case"
        exit 1
    fi
fi

jardirs=${zimbra_home}/tomcat/common/lib:${zimbra_home}/lib/jars
if [ -e ${zimbra_home}/lib/ext-common ]; then
    jardirs=${jardirs}:${zimbra_home}/lib/ext-common
fi
for jd in `find ${zimbra_home}/lib/ext -type d` ; do
    if [ ${jd} != ${zimbra_home}/lib/ext ]; then
        jardirs="${jardirs}:${jd}"
    fi
done

#
# Memory for use by JVM
#
memkb=$(zmsysmemkb)
jm=`expr $memkb '*' ${tomcat_java_heap_memory_percent} / 100 / 1024`

echo $$ > $ropid
${zimbra_java_home}/bin/java \
    -Xms${jm}m -Xmx${jm}m ${tomcat_java_options} \
    -Djava.ext.dirs=${jardirs} \
    com.zimbra.cs.backup.RestoreOfflineUtil "$@"
rm -f $ropid
