#!/bin/bash

# Copyright (c) 2012 Cloudera, Inc. All rights reserved.

# Time marker for both stderr and stdout
date; date 1>&2

cloudera_config=`dirname $0`
cloudera_config=`cd "$cloudera_config/../common"; pwd`
. ${cloudera_config}/cloudera-config.sh

# Load the parcel environment
source_parcel_environment

# attempt to find java
locate_cdh_java_home

echo "using $JAVA_HOME as JAVA_HOME"
echo "using $CDH_VERSION as CDH_VERSION"
echo "using $CDH_ZOOKEEPER_HOME as CDH_ZOOKEEPER_HOME"
echo "using $CONF_DIR as CONF_DIR"

set_zookeeper_classpath
echo "using $ZOOKEEPER_CLASSPATH as ZOOKEEPER_CLASSPATH"

export ZOOKEEPER_HOME=${CDH_ZOOKEEPER_HOME}
export ZOOKEEPER_CONF=${CONF_DIR}
echo "ZOOKEEPER_HOME is $ZOOKEEPER_HOME"
echo "configuration directory is $CONF_DIR"

export CLASSPATH=$CLASSPATH:$ZOOKEEPER_CONF:$ZOOKEEPER_HOME/*:$ZOOKEEPER_HOME/lib/*:$ZOOKEEPER_CLASSPATH

# Disable IPv6.
export JAVA_OPTS="-Djava.net.preferIPv4Stack=true $JAVA_OPTS"

if [ "init" = "$1" ]; then
  # $2 is actual argument to pass to Zk script
  # $3 is whether to ignore failure if Zk is already initialized
  IGNORE=$3
  # mirror /usr/bin/zookeeper-server-initialize
  export ZOOPIDFILE=${ZOOPIDFILE:-/var/run/zookeeper/zookeeper-server.pid}
  export ZOOCFGDIR=${ZOOKEEPER_CONF}
  # log settings are all set through ZOOKEEPER_SERVER_OPTS
  #export ZOO_LOG_DIR=/var/log/zookeeper
  #export ZOO_LOG4J_PROP=INFO,ROLLINGFILE
  ZOOKEEPER_SERVER_OPTS=$(replace_pid $ZOOKEEPER_SERVER_OPTS)
  export JVMFLAGS="${JVMFLAGS} ${ZOOKEEPER_SERVER_OPTS}"
  export ZOO_DATADIR_AUTOCREATE_DISABLE=true
  if [ "$3" != "ignoreExists" ]; then
    exec ${ZOOKEEPER_HOME}/bin/zkServer-initialize.sh $2
  else
    INIT_OUT=`${ZOOKEEPER_HOME}/bin/zkServer-initialize.sh $2`
    RET=$?
    if [ $RET -eq 0 ]; then
      exit 0 # Command exited successfully
    else
      echo $INIT_OUT | grep -q "already exists"
      if [ $? -eq 0 ]; then
        # Zk has been already initialized, ignore failure
        exit 0
      fi
      exit $RET
    fi
  fi
elif [ "cleanup" = "$1" ]; then
  # $2 is dataLogDir
  # $3 is dataDir, or "snapDir"
  # $4 is number of old snaps/logs to keep
  JAVA=$JAVA_HOME/bin/java
  exec $JAVA -cp $CLASSPATH $JAVA_OPTS -Dzookeeper.root.logger=${ZOO_LOG4J_PROP} org.apache.zookeeper.server.PurgeTxnLog "$2" "$3" -n "$4"
fi
