#!/bin/sh -e
#
# /etc/init.d/clickhouse-jdbc-bridge -- startup script for ClickHouse JDBC bridge
#
#
### BEGIN INIT INFO
# Provides:          clickhouse-jdbc-bridge
# Required-Start:    $local_fs $remote_fs $network
# Required-Stop:     $local_fs $remote_fs $network
# Should-Start:      $named
# Should-Stop:       $named
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: ClickHouse JDBC bridge
# Description:       ClickHouse JDBC bridge
### END INIT INFO

# Configuration files
#
# /etc/default/clickhouse-jdbc-bridge
#   If it exists, this is read at the start of script. It may perform any
#   sequence of shell commands, like setting relevant environment variables.
#
# Configuration variables (to define in /etc/default/clickhouse-jdbc-bridge)
#
# JAVA_HOME
#   Home of Java installation.
#
# JAVA_OPTIONS
#   Extra options to pass to the JVM
#
# BRIDGE_USER
#   if set, then used as a username to run the server as

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
NAME=clickhouse-jdbc-bridge
DESC="ClickHouse JDBC bridge"
BRIDGE_HOME=/usr/local/lib/java
BRIDGE_CONF=/etc/clickhouse-jdbc-bridge
LOGDIR="/var/log/$NAME"
START_JAR="$BRIDGE_HOME/$NAME-shaded.jar"
JVM_TMP=/var/cache/$NAME/tmp
PIDDIR="/var/run/$NAME"
PIDFILE="$PIDDIR/$NAME.pid"

if [ `id -u` -ne 0 ]; then
	echo "You need root privileges to run this script"
	exit 1
fi

. /lib/lsb/init-functions


# The following variables can be overwritten in /etc/clickhouse-jdbc-bridge/defaults

# Whether to start jetty (as a daemon) or not
NO_START=0

# Run Jetty as this user ID (default: jetty)
# Set this to an empty string to prevent Jetty from starting automatically
BRIDGE_USER=clickhouse-jdbc-bridge

# Extra options to pass to the JVM
JAVA_OPTIONS="-Xmx1G -Djava.awt.headless=true"

# This function sets the variable JDK_DIRS
find_jdks()
{
    for java_version in 9 8 7
    do
        for jvmdir in /usr/lib/jvm/java-${java_version}-openjdk-* \
                      /usr/lib/jvm/jdk-${java_version}-oracle-* \
                      /usr/lib/jvm/jre-${java_version}-oracle-* \
                      /usr/lib/jvm/java-${java_version}-oracle \
		      /usr/lib/jvm/bellsoft-java8-amd64 \
                      /usr/lib/jvm/java-*/jre
        do
            if [ -d "${jvmdir}" ]
            then
                JDK_DIRS="${JDK_DIRS} ${jvmdir}"
            fi
        done
    done

    # Add the paths for the JVMs packaged by the older versions of java-package (<< 0.52 as in Wheezy and Trusty)
    JDK_DIRS="${JDK_DIRS} /usr/lib/jvm/j2re1.7-oracle /usr/lib/jvm/j2sdk1.7-oracle"
}

# The first existing directory is used for JAVA_HOME (if JAVA_HOME is not
# defined in $DEFAULT)
JDK_DIRS="/usr/lib/jvm/default-java"
find_jdks

# Timeout in seconds for the shutdown of all webapps
BRIDGE_SHUTDOWN=10
BRIDGE_TMP=/var/cache/$NAME/data
# End of variables that can be overwritten in /etc/clickhouse-jdbc-bridge/defaults

# overwrite settings from default file
if [ -f "$DEFAULT" ]; then
	. "$DEFAULT"
fi

# Check whether jetty is still installed (it might not be if this package was
# removed and not purged)
if [ ! -r "$START_JAR" ]; then
	log_failure_msg "$NAME is not installed ($START_JAR is missing)"
	exit 1
fi

# Check whether startup has been disabled
if [ "$NO_START" != "0" -a "$1" != "stop" ]; then
	[ "$VERBOSE" != "no" ] && log_failure_msg "Not starting jetty - edit /etc/$NAME/defaults and change NO_START to be 0 (or comment it out)."
	exit 0
fi

# Look for the right JVM to use
for jdir in $JDK_DIRS; do
	if [ -d "$jdir" -a -z "${JAVA_HOME}" ]; then
		JAVA_HOME="$jdir"
	fi
done
export JAVA_HOME

export JAVA="$JAVA_HOME/bin/java"

JAVA_OPTIONS="$JAVA_OPTIONS \
  -Djava.io.tmpdir=$BRIDGE_TMP \
  -Djava.util.logging.config.file=$BRIDGE_CONF/logging.properties \
  -Duser.dir=$BRIDGE_CONF"

export JAVA_OPTIONS

# Define other required variables
ROTATELOGS=/usr/sbin/rotatelogs

##################################################
# Create /var/run directory
##################################################

if [ ! -d "$PIDDIR" ]; then
       install -d -m 0755 -o "$BRIDGE_USER" -g "$BRIDGE_USER" "$PIDDIR" >/dev/null 2>&1 || exit 1
fi


##################################################
# Check for JAVA_HOME
##################################################
if [ -z "$JAVA_HOME" ]; then
	log_failure_msg "Could not start $DESC because no Java Runtime Environment (JRE)"
	log_failure_msg "was found. Please download and install Java 8 or higher and set"
	log_failure_msg "JAVA_HOME in /etc/clickhouse-jdbc-bridge/defaults to the JDK's installation directory."
	exit 0
fi
if [ -f "${BRIDGE_CONF}/clickhouse-jdbc-bridge-env.sh" ]; then
  . "${BRIDGE_CONF}/clickhouse-jdbc-bridge-env.sh"
fi

##################################################
# Do the action
##################################################
case "$1" in
  start)
	if pidofproc -p "$PIDFILE" su > /dev/null 2>&1; then
		log_warning_msg "(already running)."
		exit 1
	else
		if [ -f $PIDFILE ] ; then
			log_warning_msg "PID file exists but bridge was not running."
		fi
    mkdir -p "$LOGDIR" || {
            log_failure_msg "could not create $DESC log directory at $LOGDIR"
            exit 1
    }
		chown -R $BRIDGE_USER:$BRIDGE_USER "$LOGDIR"

		# Remove / recreate BRIDGE_TMP directory
		rm -rf "$BRIDGE_TMP"
		mkdir "$BRIDGE_TMP" || {
			log_failure_msg "could not create $DESC temporary directory at $BRIDGE_TMP"
			exit 1
		}
		chown $BRIDGE_USER "$BRIDGE_TMP"

		# Remove / recreate JVM_TMP directory
		rm -rf "$JVM_TMP"
		mkdir "$JVM_TMP" || {
			log_failure_msg "could not create JVM temporary directory at $JVM_TMP"
			exit 1
		}

		chown $BRIDGE_USER "$JVM_TMP"

		cd "$BRIDGE_CONF"

		BRIDGE_CMD="$JAVA $JAVA_OPTIONS -jar $START_JAR"

		su -s /bin/bash "$BRIDGE_USER" -c "$BRIDGE_CMD" &
		echo "$!" > "$PIDFILE"

		sleep 2
		if pidofproc -p "$PIDFILE" su >/dev/null 2>&1; then
			log_success_msg "Started $DESC with pid $(cat $PIDFILE)"
		else
			log_failure_msg "Failed to start $DESC"
		fi
	fi
	;;

  stop)

	if pidofproc -p "$PIDFILE" su >/dev/null 2>&1; then
		killproc -p "$PIDFILE" su &&
		rm -f "$PIDFILE" &&
		rm -rf "$JVM_TMP" &&
		rm -rf "$BRIDGE_TMP/*"
	else
	    if [ -f "$PIDFILE" ]; then
		log_warning_msg "(not running but $PIDFILE exists)."
	    else
		log_warning_msg "(not running)."
	    fi
	fi
	;;

  status)

	if pidofproc -p "$PIDFILE" su >/dev/null 2>&1; then
		log_success_msg "$DESC is running with pid `cat $PIDFILE`"
	else
	    if [ -f "$PIDFILE" ]; then
		log_success_msg "$DESC is not running, but pid file exists."
	    else
		log_success_msg "$DESC is not running."
	    fi
	fi
	;;

  restart|force-reload)
	$0 stop
	$0 start
	;;

  try-restart)
	if pidofproc -p "$PIDFILE" su >/dev/null 2>&1; then
		log_success_msg "$DESC is already running with pid `cat $PIDFILE`"
		$0 stop
		$0 start
	else
		log_success_msg "${DESC} is not running"
	fi
	;;

  check)
	log_success_msg "Checking arguments for Jetty: "
	log_success_msg ""
	log_success_msg "PIDFILE        =  $PIDFILE"
	log_success_msg "JAVA_OPTIONS   =  $JAVA_OPTIONS"
	log_success_msg "JAVA           =  $JAVA"
	log_success_msg "BRIDGE_USER     =  $BRIDGE_USER"
	log_success_msg "ARGUMENTS      =  $ARGUMENTS"

	if pidofproc -p "$PIDFILE" su; then
		log_success_msg "$DESC is running with pid `cat $PIDFILE`"
		exit 0
	fi
	exit 1
	;;

  *)
	log_success_msg "Usage: $0 {start|stop|restart|force-reload|try-restart|status|check}"
	exit 1
	;;
esac

exit 0