#!/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 \
    zimbra_home 

for i in $@; do
	if [ x$found = "xtrue" ]; then
		targ="$i/ldap"
		found="false";
	fi
	if [ $i = "-t" -o $i = "--target" ]; then
		found="true"
	elif [ $i = "-del" -o $i = "--delete" ]; then
	    del="true"
	fi
done
if [ x$targ = "x" ]; then
	targ="${zimbra_home}/backup/ldap"
fi

if [ ! -f "${zimbra_home}/lib/ext/backup/zimbrabackup.jar" -a -f "${zimbra_home}/openldap/sbin/slapcat" ]; then
	# bug 7420 - backup for ldap only host
	dt=`date +%Y%m%d%H%M%S`
	d="$targ/$dt"
	/opt/zimbra/libexec/zmslapcat $d
	rm -f $d/ldap.bak.*
	exit 0
fi

tmpfile=/tmp/zmbackup.$$.out
`dirname $0`/zmjavaext -classpath ${zimbra_home}/lib/ext/backup/zimbrabackup.jar \
	com.zimbra.cs.backup.BackupUtil "$@" > $tmpfile
if [ $? -eq 0 -a x$del != "xtrue" ]; then
    r=`cat $tmpfile`
    echo $r
    for lb in `echo $r`; do
        d="$targ/$lb"
        mkdir -p $d
        /opt/zimbra/libexec/zmslapcat $d
        rm -f $d/ldap.bak.*
    done
fi
rm -f $tmpfile
