#!/bin/bash

# Copyright (c) 2013-2014 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 and place it in JAVA_HOME. The catalina.sh script expects
# to find it there.
locate_cdh_java_home

set -x

echo "using $CDH_VERSION as CDH_VERSION"

# Search-replace {{CMF_CONF_DIR}} in files
replace_conf_dir

# local replacement of subsitution variables
perl -pi -e "s#{{CMF_CONF_DIR}}#$CONF_DIR#g" $CONF_DIR/*.properties

# This script expects the following env vars to be set by CM server:
# SQOOP_SERVER_DIR: Directory containing sqoop libraries for it to work with MR/Yarn
# SQOOP_SERVER_OPTS (optional): Any additional java cmd line opts to be passed to Sqoop servers
# SQOOP_HTTP_PORT
# SQOOP_ADMIN_PORT

if [ $CDH_VERSION -ge 5 ]; then
  if [ -z $SCM_DEFINES_SCRIPTS ]; then
    TOMCAT_CONF=/etc/sqoop2/$SQOOP_SERVER_DIR
  else
    TOMCAT_CONF=$CDH_SQOOP2_HOME/../../etc/sqoop2/$SQOOP_SERVER_DIR
  fi
  export CATALINA_BASE=/var/lib/sqoop2/tomcat-deployment

  env TOMCAT_CONF=${TOMCAT_CONF} TOMCAT_DEPLOYMENT=${CATALINA_BASE} SQOOP2_HOME=${CDH_SQOOP2_HOME} \
    bash ${CDH_SQOOP2_HOME}/tomcat-deployment.sh
else
  export CATALINA_BASE=$CDH_SQOOP2_HOME/$SQOOP_SERVER_DIR
fi
export CATALINA_TMPDIR=$PWD/temp
export CATALINA_OUT=$SQOOP_LOG_DIR/sqoop.out
export CATALINA_PID=$PWD/sqoop.pid

SQOOP_SERVER_OPTS=$(replace_pid $SQOOP_SERVER_OPTS)
OPTIONS="$SQOOP_SERVER_OPTS"
OPTIONS="$OPTIONS -Dlog4j.configuration=file:///$CONF_DIR/log4j.properties"
OPTIONS="$OPTIONS -Dsqoop.config.dir=$CONF_DIR"
OPTIONS="$OPTIONS -Djava.net.preferIPv4Stack=true" # Disable IPv6.
OPTIONS="$OPTIONS -Dsqoop.http.port=$SQOOP_HTTP_PORT"
OPTIONS="$OPTIONS -Dsqoop.admin.port=$SQOOP_ADMIN_PORT"
CATALINA_OPTS=$(replace_pid $CATALINA_OPTS)
export CATALINA_OPTS="$OPTIONS $CATALINA_OPTS"

# Specify config file for catalina logs
export LOGGING_CONFIG="-Djava.util.logging.config.file=$CONF_DIR/catalina_logging.properties"

# Create temp directory for Catalina
mkdir -p $CATALINA_TMPDIR

# Copy the JDBC jars.
# This is useful only for CDH4.3+, but since we can't differentiate between minor versions,
# we do it for all CDH4 versions. It is harmless to copy these for CDH 4.2.
EXT_LIBS_DIR=/var/lib/sqoop2
cp $CLOUDERA_MYSQL_CONNECTOR_JAR $EXT_LIBS_DIR 2>/dev/null
cp $CLOUDERA_POSTGRESQL_JDBC_JAR $EXT_LIBS_DIR 2>/dev/null
cp $CLOUDERA_ORACLE_CONNECTOR_JAR $EXT_LIBS_DIR 2>/dev/null

# TODO Call different command when it's available in sqoop
if [ "$1" == upgrade -o "$1" == "create-database" ]; then
  export JAVA_OPTS="$CATALINA_OPTS $JAVA_OPTS"
  exec $TOMCAT_HOME/bin/tool-wrapper.sh -server org.apache.sqoop.tomcat.TomcatToolRunner upgrade
else
  exec $TOMCAT_HOME/bin/catalina.sh run
fi
