#!/bin/bash
# Copyright (c) 2014 Cloudera, Inc. All rights reserved.

# debug
set -x

# 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

HADOOP_CLIENT_OPTS=$(replace_pid $HADOOP_CLIENT_OPTS)

if [ "$CDH_VERSION" -ge "4" ]; then
  # Disable IPv6. This is automatically done by bin/hadoop for CDH3 clients.
  export HADOOP_CLIENT_OPTS="-Djava.net.preferIPv4Stack=true $HADOOP_CLIENT_OPTS"
fi

echo "using $JAVA_HOME as JAVA_HOME"
echo "using $CDH_VERSION as CDH_VERSION"

export HADOOP_HOME=$CDH_HADOOP_HOME
export SENTRY_HOME=$CDH_SENTRY_HOME
export HADOOP_CONF_DIR=$CONF_DIR
export HIVE_CONF_DIR="$CONF_DIR/$HIVE_CONF_DIR_NAME"


JDBC_JARS="$CLOUDERA_MYSQL_CONNECTOR_JAR:$CLOUDERA_POSTGRESQL_JDBC_JAR:$CLOUDERA_ORACLE_CONNECTOR_JAR"
export HADOOP_CLASSPATH=${HADOOP_CLASSPATH}:${JDBC_JARS}

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

if [[ "$1" == initSchema ]]; then
  # schema-tool isn't idempotent, so exit if there are any existing tables
  skip_if_tables_exist sentry_db.properties
fi
if [[ "$1" == initSchema || "$1" == upgradeSchema ]]; then
  SCHEMATOOL_DBTYPE=$SENTRY_SERVER_DATABASE_TYPE
  if [[ "$SENTRY_SERVER_DATABASE_TYPE" == postgresql ]]; then
    SCHEMATOOL_DBTYPE="postgres"
    # OPSAPS-16280 tell schematool to be compatible with postgres 8.1
    POSTGRESQL81_WORKAROUND="-dbOpts postgres.filter.81"
  fi

  exec bash -x $SENTRY_HOME/bin/sentry --command schema-tool --verbose --conffile $CONF_DIR/sentry-site.xml --dbType $SCHEMATOOL_DBTYPE --$1 $POSTGRESQL81_WORKAROUND
else
  exec $SENTRY_HOME/bin/sentry --command service --log4jConf $CONF_DIR/sentry-log4j.properties -conffile $CONF_DIR/sentry-site.xml
fi
