#!/bin/sh

# Shell functions sourced from /etc/rc.status:
#      rc_check         check and set local and overall rc status
#      rc_status        check and set local and overall rc status
#      rc_status -v     ditto but be verbose in local rc status
#      rc_status -v -r  ditto and clear the local rc status
#      rc_failed        set local and overall rc status to failed
#      rc_reset         clear local rc status (overall remains)
#      rc_exit          exit appropriate to overall rc status
. /etc/rc.status

function bail() {
        rc_failed $1
        shift
        echo $@
        rc_exit
}

test "${1}" = "${COMPANY}-${SERVICE}" || bail 2 "Script must start with ${COMPANY}-"
shift

test -x /etc/init.d/${COMPANY}-${SERVICE} || bail 2 "Script must be /etc/init.d/${COMPANY}-${SERVICE}"


NAME=${COMPANY}-${SERVICE}
JAVA_CMD=/etc/alternatives/java
test -x ${JAVA_CMD} || bail 2 "${JAVA_CMD} not found or not executable"

RUN_USER="${SERVICE}"
RUN_GROUP="${COMPANY}"

JAVA_OPTS="-Xmx64m"

for each in "${COMPANY}-Environment" "${COMPANY}-Node" "${COMPANY}-${SERVICE}"; do
        if [ -f /etc/sysconfig/${each} ]; then
          echo "Loading $each"
          . /etc/sysconfig/${each}
        fi
done

test -n "${RUN_USER}" || bail 2 "RUN_USER must be set"
test -n "${BIND_ADDRESS}" || bail 2 "BIND_ADDRESS must be set"
test -n "${PORT}" || bail 2 "PORT must be set"
test -n "${REPOSITORY_USER}" || bail 2 "REPOSITORY_USER must be set"
test -n "${REPOSITORY_PASSWORD}" || bail 2 "REPOSITORY_PASSWORD must be set"
test -n "${REPOSITORY_URL}" || bail 2 "REPOSITORY_URL must be set"
test -n "${DEPLOYER_VERSION}" || bail 2 "DEPLOYER_VERSION must be set"

test -n "${SERVICE_VERSION}" || bail 2 "SERVICE_VERSION must be set"
test -n "${SERVICE_GROUP}" || bail 2 "SERVICE_GROUP must be set"
test -n "${SERVICE_ARTIFACT}" || bail 2 "SERVICE_ARTIFACT must be set"

SERVICE_HOME=/var/opt/${NAME}
test -d ${SERVICE_HOME} || bail 2 "${SERVICE_HOME} not found"
COMPANY_HOME=/opt/${COMPANY}
test -d ${COMPANY_HOME} || bail 2 "${COMPANY_HOME} not found"

WORKING_DIRECTORY=${SERVICE_HOME}
LOGFILE=${WORKING_DIRECTORY}/console.log
PIDFILE=/var/run/${COMPANY}-${SERVICE}.pid

DEPLOYER_GROUP="net/stickycode/deploy"
DEPLOYER_ARTIFACT="sticky-deployer-tomcat6"
DEPLOYER_JAR="sticky-deployer-tomcat6-${DEPLOYER_VERSION}-minimal.jar"

if ! test -f ${COMPANY_HOME}/${DEPLOYER_JAR}; then
  DEPLOYER_REMOTE="${REPOSITORY_URL}/${DEPLOYER_GROUP}/${DEPLOYER_ARTIFACT}/${DEPLOYER_VERSION}/${DEPLOYER_JAR}"
  echo "Fetching $DEPLOYER_REMOTE"
	curl --fail --insecure --user ${REPOSITORY_USER}:${REPOSITORY_PASSWORD} \
		${DEPLOYER_REMOTE} \
		--output ${COMPANY_HOME}/${DEPLOYER_JAR}
	if ! test -f ${COMPANY_HOME}/${DEPLOYER_JAR}; then
		bail 2 "Failed to download deployer, check version"
	fi
	curl --fail --insecure --user ${REPOSITORY_USER}:${REPOSITORY_PASSWORD} \
		${DEPLOYER_REMOTE}.sha1 \
		--output ${COMPANY_HOME}/${DEPLOYER_JAR}.sha1
	echo "  ${DEPLOYER_JAR}" >> ${COMPANY_HOME}/${DEPLOYER_JAR}.sha1
fi
sha1sum --check ${COMPANY_HOME}/${DEPLOYER_JAR}.sha1 || bail 2 "Could not verify deployer checksum"

SERVICE_WAR="${SERVICE_ARTIFACT}-${SERVICE_VERSION}-application.war"
if ! test -f ${SERVICE_HOME}/${SERVICE_WAR}; then
  SERVICE_REMOTE="${REPOSITORY_URL}/${SERVICE_GROUP}/${SERVICE_ARTIFACT}/${SERVICE_VERSION}/${SERVICE_WAR}"
  echo "Fetching $SERVICE_REMOTE"
	curl --fail --insecure --user ${REPOSITORY_USER}:${REPOSITORY_PASSWORD} \
		${SERVICE_REMOTE} \
		--output ${SERVICE_HOME}/${SERVICE_WAR}
	if ! test -f ${SERVICE_HOME}/${SERVICE_WAR}; then
		bail 2 "Failed to download ${SERVICE}, check version ${SERVICE_VERSION}"
	fi
	curl --fail --insecure --user ${REPOSITORY_USER}:${REPOSITORY_PASSWORD} \
		${SERVICE_REMOTE}.sha1 \
		--output ${SERVICE_HOME}/${SERVICE_WAR}.sha1
	if ! test -f ${SERVICE_HOME}/${SERVICE_WAR}; then
		bail 2 "Failed to download ${SERVICE} checksum"
	fi
	echo "  ${SERVICE_HOME}/${SERVICE_WAR}" >> ${SERVICE_HOME}/${SERVICE_WAR}.sha1
fi
sha1sum --check ${SERVICE_HOME}/${SERVICE_WAR}.sha1 || bail 2 "Could not verify ${SERVICE} checksum"

# The echo return value for success (defined in /etc/rc.config).
rc_reset

# Return values acc. to LSB for all commands but status:
# 0 - success
# 1 - generic or unspecified error
# 2 - invalid or excess argument(s)
# 3 - unimplemented feature (e.g. "reload")
# 4 - insufficient privilege
# 5 - program is not installed
# 6 - program is not configured
# 7 - program is not running
#
# Note that starting an already running service, stopping
# or restarting a not-running service as well as the restart
# with force-reload (in case signalling is not supported) are
# considered a success.

case "$1" in
    start)
        echo -n "Starting $NAME"
        startproc -u ${RUN_USER} -g ${RUN_GROUP} -p ${PIDFILE} -l ${LOGFILE} \
        	${JAVA_CMD} ${JAVA_OPTS} \
        	-jar ${COMPANY_HOME}/${DEPLOYER_JAR} \
        	${SERVICE_WAR} ${PORT} ${BIND_ADDRESS} ${WORKING_DIRECTORY}
        rc_status -v
    ;;

    stop)
        echo -n "Stopping $NAME"
        killproc -TERM -p ${PIDFILE} -t30 ${JAVA_CMD}
        rc_status -v
    ;;

    try-restart)
        ## Stop the service and if this succeeds (i.e. the
        ## service was running before), start it again.
        $0 status >/dev/null &&  $0 restart

        # Remember status and be quiet
        rc_status
        ;;

    restart)
        ## Stop the service and regardless of whether it was
        ## running or not, start it again.
        $0 stop
        $0 start

        # Remember status and be quiet
        rc_status
        ;;

    force-reload)
        ## Signal the daemon to reload its config. Most daemons
        ## do this on signal 1 (SIGHUP).
        ## If it does not support it, restart.

        echo -n "Reload ${NAME}"
        ## if it supports it:
        killproc -HUP -p ${PIDFILE} ${JAVA_CMD}
        rc_status -v
        ;;

    reload)
        ## Like force-reload, but if daemon does not support
        ## signalling, do nothing (!)

        # If it supports signalling:
        echo -n "Reload ${NAME}: "
        killproc -HUP -p ${PIDFILE} ${JAVA_CMD}
        rc_status -v
        ;;
    status)
        echo -n "Status ${NAME}: "
        ## Check status with checkproc(8), if process is running
        ## checkproc will return with exit status 0.

        # Status has a slightly different for the status command:
        # 0 - service running
        # 1 - service dead, but /var/run/  pid  file exists
        # 2 - service dead, but /var/lock/ lock file exists
        # 3 - service not running

        # NOTE: checkproc returns LSB compliant status values.
        checkproc  -p ${PIDFILE} ${JAVA_CMD}
        rc_status -v
        ;;
    *)
        echo "Usage: $0 {start|stop|status|try-restart|restart|force-reload|reload|once}"
        exit 1
                    ;;
esac

# Inform the caller not only verbosely and set an exit status.
rc_exit
