#!/usr/bin/env bash
#
#/**
# * Copyright 2007 The Apache Software Foundation
# *
# * Licensed to the Apache Software Foundation (ASF) under one
# * or more contributor license agreements.  See the NOTICE file
# * distributed with this work for additional information
# * regarding copyright ownership.  The ASF licenses this file
# * to you under the Apache License, Version 2.0 (the
# * "License"); you may not use this file except in compliance
# * with the License.  You may obtain a copy of the License at
# *
# *     http://www.apache.org/licenses/LICENSE-2.0
# *
# * Unless required by applicable law or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
# */

# check if net.ipv6.bindv6only is set to 1
bindv6only=$(/sbin/sysctl -n net.ipv6.bindv6only 2> /dev/null)
if [ -n "$bindv6only" ] && [ "$bindv6only" -eq "1" ]
then
  echo "Error: \"net.ipv6.bindv6only\" is set to 1 - Java networking could be broken"
  echo "For more info (the following page also applies to hedwig): http://wiki.apache.org/hadoop/HadoopIPv6"
  exit 1
fi

# See the following page for extensive details on setting
# up the JVM to accept JMX remote management:
# http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html
# by default we allow local JMX connections
if [ "x$JMXLOCALONLY" = "x" ]
then
    JMXLOCALONLY=false
fi

if [ "x$JMXDISABLE" = "x" ]
then
    echo "JMX enabled by default" >&2
    # for some reason these two options are necessary on jdk6 on Ubuntu
    #   accord to the docs they are not necessary, but otw jconsole cannot
    #   do a local attach
    JMX_ARGS="-Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.local.only=$JMXLOCALONLY"
else
    echo "JMX disabled by user request" >&2
fi

BINDIR=`dirname "$0"`
HW_HOME=`cd $BINDIR/..;pwd`

DEFAULT_CONF=$HW_HOME/conf/hw_server.conf
DEFAULT_REGION_CLIENT_CONF=$HW_HOME/conf/hw_region_client.conf
DEFAULT_LOG_CONF=$HW_HOME/conf/log4j.properties

. $HW_HOME/conf/hwenv.sh

# Check for the java to use
if [[ -z $JAVA_HOME ]]; then
    JAVA=$(which java)
    if [ $? = 0 ]; then
        echo "JAVA_HOME not set, using java from PATH. ($JAVA)"
    else
        echo "Error: JAVA_HOME not set, and no java executable found in $PATH." 1>&2
        exit 1
    fi
else
    JAVA=$JAVA_HOME/bin/java
fi

RELEASE_JAR=`ls $HW_HOME/hedwig-server-*.jar 2> /dev/null | tail -1`
if [ $? == 0 ]; then
    HEDWIG_JAR=$RELEASE_JAR
fi

BUILT_JAR=`ls $HW_HOME/target/hedwig-server-*.jar 2> /dev/null | tail -1`
if [ $? != 0 ] && [ ! -e "$HEDWIG_JAR" ]; then 
    echo "\nCouldn't find hedwig jar.";
    echo "Make sure you've run 'mvn package'\n";
    exit 1;
elif [ -e "$BUILT_JAR" ]; then
    HEDWIG_JAR=$BUILT_JAR
fi

add_maven_deps_to_classpath() {
    MVN="mvn"
    if [ "$MAVEN_HOME" != "" ]; then
	MVN=${MAVEN_HOME}/bin/mvn
    fi
    
    # Need to generate classpath from maven pom. This is costly so generate it
    # and cache it. Save the file into our target dir so a mvn clean will get
    # clean it up and force us create a new one.
    f="${HW_HOME}/target/cached_classpath.txt"
    if [ ! -f "${f}" ]
    then
	${MVN} -f "${HW_HOME}/pom.xml" dependency:build-classpath -Dmdep.outputFile="${f}" &> /dev/null
    fi
    HEDWIG_CLASSPATH=${CLASSPATH}:`cat "${f}"`
}

if [ -d "$HW_HOME/lib" ]; then
    for i in $HW_HOME/lib/*.jar; do
	HEDWIG_CLASSPATH=$HEDWIG_CLASSPATH:$i
    done
else
    add_maven_deps_to_classpath
fi

hedwig_help() {
    cat <<EOF
Usage: hedwig <command>
where command is one of:
    server           Run the hedwig server
    console          Run the hedwig admin console
    help             This help message

or command is the full name of a class with a defined main() method.

Environment variables:
   HEDWIG_SERVER_CONF           Hedwig server configuration file (default $DEFAULT_CONF)
   HEDWIG_REGION_CLIENT_CONF           Configuration file for the hedwig client used by the
                                region manager (default $DEFAULT_REGION_CLIENT_CONF)
   HEDWIG_CONSOLE_SERVER_CONF   Server part configuration for hedwig console,
                                used for metadata management (defaults to HEDWIG_SERVER_CONF)
   HEDWIG_CONSOLE_CLIENT_CONF   Client part configuration for hedwig console,
                                used for interacting with hub server.
   HEDWIG_LOG_CONF              Log4j configuration file (default $DEFAULT_LOG_CONF)
   HEDWIG_ROOT_LOGGER           Root logger for hedwig
   HEDWIG_LOG_DIR               Log directory to store log files for hedwig server
   HEDWIG_LOG_FILE              Log file name
   HEDWIG_EXTRA_OPTS            Extra options to be passed to the jvm

These variable can also be set in conf/hwenv.sh
EOF
}

# if no args specified, show usage
if [ $# = 0 ]; then
    hedwig_help;
    exit 1;
fi

# get arguments
COMMAND=$1
shift

if [ -z "$HEDWIG_SERVER_CONF" ]; then
    HEDWIG_SERVER_CONF=$DEFAULT_CONF;
fi

if [ -z "$HEDWIG_REGION_CLIENT_CONF" ]; then
    HEDWIG_REGION_CLIENT_CONF=$DEFAULT_REGION_CLIENT_CONF;
fi

if [ -z "$HEDWIG_LOG_CONF" ]; then
    HEDWIG_LOG_CONF=$DEFAULT_LOG_CONF
fi

HEDWIG_CLASSPATH="$HEDWIG_JAR:$HEDWIG_CLASSPATH"

if [ "$HEDWIG_LOG_CONF" != "" ]; then
    HEDWIG_CLASSPATH="`dirname $HEDWIG_LOG_CONF`:$HEDWIG_CLASSPATH"
    OPTS="$OPTS -Dlog4j.configuration=`basename $HEDWIG_LOG_CONF`"
fi
OPTS="-cp $HEDWIG_CLASSPATH $OPTS $HEDWIG_EXTRA_OPTS"

# Disable ipv6 as it can cause issues
OPTS="$OPTS -Djava.net.preferIPv4Stack=true"

# log directory & file
HEDWIG_ROOT_LOGGER=${HEDWIG_ROOT_LOGGER:-"INFO,CONSOLE"}
HEDWIG_LOG_DIR=${HEDWIG_LOG_DIR:-"$HW_HOME/logs"}
HEDWIG_LOG_FILE=${HEDWIG_LOG_FILE:-"hedwig-server.log"}

# Configure log configuration system properties
OPTS="$OPTS -Dhedwig.root.logger=$HEDWIG_ROOT_LOGGER"
OPTS="$OPTS -Dhedwig.log.dir=$HEDWIG_LOG_DIR"
OPTS="$OPTS -Dhedwig.log.file=$HEDWIG_LOG_FILE"

# Change to HW_HOME to support relative paths
cd "$BK_HOME"
if [ $COMMAND == "server" ]; then
    exec $JAVA $OPTS $JMX_ARGS org.apache.hedwig.server.netty.PubSubServer $HEDWIG_SERVER_CONF $HEDWIG_REGION_CLIENT_CONF $@
elif [ $COMMAND == "console" ]; then
    # hedwig console configuration server part
    if [ -z "$HEDWIG_CONSOLE_SERVER_CONF" ]; then
        HEDWIG_CONSOLE_SERVER_CONF=$HEDWIG_SERVER_CONF
    fi
    # hedwig console configuration client part
    if [ -n "$HEDWIG_CONSOLE_CLIENT_CONF" ]; then
        HEDWIG_CONSOLE_CLIENT_OPTIONS="-client-cfg $HEDWIG_CONSOLE_CLIENT_CONF"
    fi
    exec $JAVA $OPTS org.apache.hedwig.admin.console.HedwigConsole -server-cfg $HEDWIG_CONSOLE_SERVER_CONF $HEDWIG_CONSOLE_CLIENT_OPTIONS $@
elif [ $COMMAND == "help" ]; then
    hedwig_help;
else
    exec $JAVA $OPTS $COMMAND $@
fi


