#!/bin/bash

# Copyright (c) 2011-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

if [ "$JAVA_HOME" != "" ]; then
  JAVA="$JAVA_HOME/bin/java"
fi

MYID=$1
DATA_DIR=$2

ZOOKEEPER_SERVER_OPTS=$(replace_pid $ZOOKEEPER_SERVER_OPTS)

export ZOOKEEPER_HOME=$CDH_ZOOKEEPER_HOME
echo "using $JAVA_HOME as JAVA_HOME"
echo "CDH_VERSION is $CDH_VERSION"
echo "ZOOKEEPER_HOME is $ZOOKEEPER_HOME"
echo "configuration directory is $CONF_DIR"
echo "server id (myid) is $MYID"
echo "data directory is $DATA_DIR"

set_zookeeper_classpath

if [ ! -d "$DATA_DIR" ]; then
    mkdir $DATA_DIR
fi

echo $MYID > $DATA_DIR/myid

# check if a jaas config file is provided for security
if [ "$JAAS_FILE" != "" ]; then
  echo "jaas config file is $JAAS_FILE"
  ZOOKEEPER_SERVER_OPTS="-Djava.security.auth.login.config=$CONF_DIR/$JAAS_FILE $ZOOKEEPER_SERVER_OPTS"
fi

# check if jmx password auth config files are provided
if [ "$JMX_AUTH_ACCESS_FILE" != "" ]; then
  echo "jmx auth access config file is $JMX_AUTH_ACCESS_FILE"
  # The password and access file permissions need to be constrained to
  # the user starting the process. If not, the process will not start.
  chmod 400 $CONF_DIR/$JMX_AUTH_PASSWORD_FILE
  chmod 400 $CONF_DIR/$JMX_AUTH_ACCESS_FILE
  ZOOKEEPER_SERVER_OPTS=" -Dcom.sun.management.jmxremote.password.file=$CONF_DIR/$JMX_AUTH_PASSWORD_FILE -Dcom.sun.management.jmxremote.access.file=$CONF_DIR/$JMX_AUTH_ACCESS_FILE $ZOOKEEPER_SERVER_OPTS"
fi

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

exec $JAVA -cp $CONF_DIR:$ZOOKEEPER_HOME/lib/log4j.jar:$ZOOKEEPER_HOME/build/*:$ZOOKEEPER_HOME/build/lib/*:$ZOOKEEPER_HOME/*:$ZOOKEEPER_HOME/lib/*:$ZOOKEEPER_CLASSPATH $ZOOKEEPER_SERVER_OPTS org.apache.zookeeper.server.quorum.QuorumPeerMain $CONF_DIR/zoo.cfg
