#!/bin/sh
#
# chkconfig: 345 80 20
# description: Artifactory on Jetty
# processname: artifactory
# pidfile: /var/run/artifactory.pid
#
### BEGIN INIT INFO
# Provides:          artifactory
# Required-Start:    $remote_fs $syslog $network
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start Artifactory at boot time
# Description:       Manages the services needed to run Artifactory - a Maven Proxy
### END INIT INFO 
# Startup script for artifactory under *nix systems (it works under NT/cygwin too).
#
# Configuration files
#
# /etc/artifactory/default
#   If it exists, this is read at the start of script. It may perform any
#   sequence of shell commands, like setting relevant environment variables.
#   It is recommended to et the JAVA_HOME and ARTIFACTORY_HOME there.
#   An example file "artifactory.default" is provided with this file.
#
# $HOME/.artifactory
#   If it exists, this is read at the start of script. It may perform any
#   sequence of shell commands, like setting relevant environment variables.
#
# /etc/jetty.conf
#   If found, and no configurations were given on the command line,
#   the file will be used as this script's configuration.
#   Each line in the file may contain:
#     - A comment denoted by the pound (#) sign as first non-blank character.
#     - The path to a regular file, which will be passed to jetty as a
#       config.xml file.
#     - The path to a directory. Each *.xml file in the directory will be
#       passed to jetty as a config.xml file.
#
#   The files will be checked for existence before being passed to jetty.
#
# $ARTIFACTORY_HOME/etc/jetty.xml
#   If found, used as this script's configuration file, but only if
#   /etc/jetty.conf was not present. See above.
#
# Configuration variables
#
# JAVA_HOME
#   Home of Java installation.
#
# JAVA
#   Command to invoke Java. If not set, $JAVA_HOME/bin/java will be
#   used.
#
# JAVA_OPTIONS
#   Extra options to pass to the JVM
#
# ARTIFACTORY_HOME
#   Where Artifactory is installed. If not set, the script will try go
#   guess it by first looking at the invocation path for the script,
#   and then by looking in standard locations as $HOME/opt/artifactory
#   and /opt/artifactory. The java system property "artifactory.home"
#   will be set to this value for use by configure.xml files, f.e.:
#
#    <Arg><SystemProperty name="artifactory.home" default="."/>/webapps/artifactory.war</Arg>
#
# ARTIFACTORY_CONSOLE
#   Where Artifactory console output should go. Defaults to first writeable of
#      ${ARTIFACTORY_HOME}/logs/consoleout.log
#      /dev/console
#      /dev/tty
#
# ARTIFACTORY_USER
#   The name of the user that will run the java jetty process. The data, backup and logs
#   folders under ARTIFACTORY_HOME should be writable by this user.
#   if left empty will run without changing user (no su -).
#
# JETTY_PORT
#   Override the default port for Jetty servers. If not set then the
#   default value in the xml configuration file will be used. The java
#   system property "jetty.port" will be set to this value for use in
#   configure.xml files. For example, the following idiom is widely
#   used in the demo config files to respect this property in Listener
#   configuration elements:
#
#    <Set name="Port"><SystemProperty name="jetty.port" default="8081"/></Set>
#
#   Note: that the config file could ignore this property simply by saying:
#
#    <Set name="Port">8081</Set>
#
# ARTIFACTORY_RUN
#   Where the artifactory.pid file should be stored. It defaults to the
#   first available of /var/run, /usr/var/run, and /tmp if not set.
#
# ARTIFACTORY_PID
#   The Jetty PID file, defaults to $ARTIFACTORY_RUN/artifactory.pid
#
# JETTY_ARGS
#   The default arguments to pass to jetty.
#

usage()
{
    echo "Usage: $0 {start|stop|run|restart|check|supervise} [ CONFIGS ... ] "
    exit 1
}

[ $# -gt 0 ] || usage

TMPJ=/tmp/j$$

##################################################
# Get the action & configs
##################################################

ACTION=$1
shift
ARGS="$*"
CONFIGS=""

##################################################
# Find directory function
##################################################
findDirectory()
{
    OP=$1
    shift
    for L in $* ; do
        [ $OP $L ] || continue
        echo $L
        break
    done
}


##################################################
# See if there's a default configuration file
##################################################
if [ -f /etc/artifactory/default ] ; then
  . /etc/artifactory/default
fi

##################################################
# See if there's a user-specific configuration file
##################################################
if [ -f $HOME/.artifactory ] ; then
  . $HOME/.artifactory
fi


##################################################
# Artifactory start jar file
##################################################
ARTIFACTORY_START_FILE="bin/artifactory.sh"


##################################################
# Try to determine ARTIFACTORY_HOME if not set
##################################################
if [ -z "$ARTIFACTORY_HOME" ]
then
  ARTIFACTORY_HOME_1=`dirname "$0"`
  ARTIFACTORY_HOME_1=`dirname "$ARTIFACTORY_HOME_1"`
  if [ -f "${ARTIFACTORY_HOME_1}/${ARTIFACTORY_START_FILE}" ] ;
  then
     ARTIFACTORY_HOME=${ARTIFACTORY_HOME_1}
  fi
fi


##################################################
# if no ARTIFACTORY_HOME, search likely locations.
##################################################
if [ "$ARTIFACTORY_HOME" = "" ] ; then
  STANDARD_LOCATIONS="           \
        $HOME                    \
        $HOME/src                \
        ${HOME}/opt/             \
        /opt                     \
        /java                    \
        /usr/share               \
        /usr/share/java          \
        /usr/local               \
        /usr/local/share         \
        /usr/local/share/java    \
        /home                    \
        "
  ARTIFACTORY_DIR_NAMES="        \
        artifactory              \
        artifactory.*            \
        artifactory-*            \
        "

  ARTIFACTORY_HOME=
  for L in $STANDARD_LOCATIONS
  do
     for N in $ARTIFACTORY_DIR_NAMES
     do
         if [ -d $L/$N ] && [ -f "$L/${N}/${ARTIFACTORY_START_FILE}" ] ;
         then
            ARTIFACTORY_HOME="$L/$N"
            echo "Defaulting ARTIFACTORY_HOME to $ARTIFACTORY_HOME"
         fi
     done
     [ ! -z "$ARTIFACTORY_HOME" ] && break
  done
fi

##################################################
# No ARTIFACTORY_HOME yet? We're out of luck!
##################################################
if [ -z "$ARTIFACTORY_HOME" ] ; then
    echo "** ERROR: ARTIFACTORY_HOME not set, you need to set it or install in a standard location"
    exit 1
fi

#####################################################
# Check that jetty is where we think it is
#####################################################
if [ ! -r $ARTIFACTORY_HOME/$ARTIFACTORY_START_FILE ]
then
   echo "** ERROR: Oops! Artifactory doesn't appear to be installed in $ARTIFACTORY_HOME"
   echo "** ERROR:  $ARTIFACTORY_HOME/$ARTIFACTORY_START_FILE is not readable!"
   exit 1
fi


###########################################################
# Get the list of config.xml files from the command line.
###########################################################
if [ ! -z "$ARGS" ]
then
  for A in $ARGS
  do
    if [ -f $A ]
    then
       CONF="$A"
    elif [ -f $ARTIFACTORY_HOME/etc/$A ]
    then
       CONF="$ARTIFACTORY_HOME/etc/$A"
    elif [ -f ${A}.xml ]
    then
       CONF="${A}.xml"
    elif [ -f $ARTIFACTORY_HOME/etc/${A}.xml ]
    then
       CONF="$ARTIFACTORY_HOME/etc/${A}.xml"
    else
       echo "** ERROR: Cannot find configuration '$A' specified in the command line."
       exit 1
    fi
    if [ ! -r $CONF ]
    then
       echo "** ERROR: Cannot read configuration '$A' specified in the command line."
       exit 1
    fi
    CONFIGS="$CONFIGS $CONF"
  done
fi

##################################################
# If ARTIFACTORY_USER set make sure the current user
# is root or some very peculiar errors appears.
##################################################
if [ -n "$ARTIFACTORY_USER" ]
then
  curUser=`id -nu`
  if [ "$curUser" != "root" ]
  then
    echo "** ERROR: Only root user can change execution user to $ARTIFACTORY_USER"
    exit 1
  fi
fi

##################################################
# Try to find this script's configuration file,
# but only if no configurations were given on the
# command line.
##################################################
if [ -z "$JETTY_CONF" ]
then
  if [ -f /etc/jetty.conf ]
  then
     JETTY_CONF=/etc/jetty.conf
  elif [ -f "${ARTIFACTORY_HOME}/etc/jetty.conf" ]
  then
     JETTY_CONF="${ARTIFACTORY_HOME}/etc/jetty.conf"
  fi
fi

##################################################
# Read the configuration file if one exists
##################################################
CONFIG_LINES=
if [ -z "$CONFIGS" ] && [ -f "$JETTY_CONF" ] && [ -r "$JETTY_CONF" ]
then
  CONFIG_LINES=`cat $JETTY_CONF | grep -v "^[:space:]*#" | tr "\n" " "`
fi

##################################################
# Get the list of config.xml files from jetty.conf
##################################################
if [ ! -z "${CONFIG_LINES}" ]
then
  for CONF in ${CONFIG_LINES}
  do
    if [ ! -r "$CONF" ]
    then
      echo "** WARNING: Cannot read '$CONF' specified in '$JETTY_CONF'"
    elif [ -f "$CONF" ]
    then
      # assume it's a configure.xml file
      CONFIGS="$CONFIGS $CONF"
    elif [ -d "$CONF" ]
    then
      # assume it's a directory with configure.xml files
      # for example: /etc/jetty.d/
      # sort the files before adding them to the list of CONFIGS
      XML_FILES=`ls ${CONF}/*.xml | sort | tr "\n" " "`
      for FILE in ${XML_FILES}
      do
         if [ -r "$FILE" ] && [ -f "$FILE" ]
         then
            CONFIGS="$CONFIGS $FILE"
         else
           echo "** WARNING: Cannot read '$FILE' specified in '$JETTY_CONF'"
         fi
      done
    else
      echo "** WARNING: Don''t know what to do with '$CONF' specified in '$JETTY_CONF'"
    fi
  done
fi

#####################################################
# Run the standard server if there's nothing else to run
#####################################################
if [ -z "$CONFIGS" ]
then
    CONFIGS="${ARTIFACTORY_HOME}/etc/jetty.xml"
fi


#####################################################
# Find a location for the pid file
#####################################################
if [  -z "$ARTIFACTORY_RUN" ]
then
  ARTIFACTORY_RUN=`findDirectory -w /var/run /usr/var/run /tmp`
fi

#####################################################
# Find a PID for the pid file
#####################################################
if [  -z "$ARTIFACTORY_PID" ]
then
  ARTIFACTORY_PID="$ARTIFACTORY_RUN/artifactory.pid"
fi

#####################################################
# Find a location for the jetty console
#####################################################
if [  -z "$ARTIFACTORY_CONSOLE" ]
then
  export ARTIFACTORY_CONSOLE=${ARTIFACTORY_HOME}/logs/consoleout.log
  touch ${ARTIFACTORY_CONSOLE} 2> /dev/null
  if [ -n "$ARTIFACTORY_USER" ]; then
    chown ${ARTIFACTORY_USER} ${ARTIFACTORY_CONSOLE}
  fi
  echo "Created output file $ARTIFACTORY_CONSOLE"
else
 touch ${ARTIFACTORY_CONSOLE} 2> /dev/null
 if [ -n "$ARTIFACTORY_USER" ]; then
   chown ${ARTIFACTORY_USER} ${ARTIFACTORY_CONSOLE}
   echo "Changed owner of $ARTIFACTORY_CONSOLE to $ARTIFACTORY_USER"
 fi
fi

#####################################################
# Create the jetty work dir
#####################################################
if [ ! -d "${ARTIFACTORY_HOME}/work" ]
then
  mkdir ${ARTIFACTORY_HOME}/work 2> /dev/null
  if [ -n "$ARTIFACTORY_USER" ]
  then
    chown ${ARTIFACTORY_USER} -R ${ARTIFACTORY_HOME}/work/
  fi
fi

##################################################
# Check for JAVA_HOME
##################################################
if [ -z "$JAVA_HOME" ]
then
    # If a java runtime is not defined, search the following
    # directories for a JVM and sort by version. Use the highest
    # version number.

    # Java search path
    JAVA_LOCATIONS="\
        /usr/bin \
        /usr/local/bin \
        /usr/local/java \
        /usr/local/jdk \
        /usr/local/jre \
        /opt/java \
        /opt/jdk \
        /opt/jre \
    "
    JAVA_NAMES="java jre kaffe"
    for N in $JAVA_NAMES ; do
        for L in $JAVA_LOCATIONS ; do
            [ -d $L ] || continue
            find $L -name "$N" ! -type d | grep -v threads | while read J ; do
                [ -x $J ] || continue
                VERSION=`eval $J -version 2>&1`
                [ $? = 0 ] || continue
                VERSION=`expr "$VERSION" : '.*"\(1.[0-9\.]*\)"'`
                [ "$VERSION" = "" ] && continue
                expr $VERSION \< 1.5 >/dev/null && continue
                echo $VERSION:$J
            done
        done
    done | sort | tail -1 > $TMPJ
    JAVA=`cat $TMPJ | cut -d: -f2`
    JVERSION=`cat $TMPJ | cut -d: -f1`

    if [ -z "$JAVA" ]
    then
        JAVA_HOME=
    else
        JAVA_HOME=`dirname $JAVA`
    fi
    while [ ! -z "$JAVA_HOME" -a "$JAVA_HOME" != "/" -a ! -f "$JAVA_HOME/lib/tools.jar" ] ; do
        JAVA_HOME=`dirname $JAVA_HOME`
    done
    [ "$JAVA_HOME" = "" ] && JAVA_HOME=

    echo "Found JAVA=$JAVA in JAVA_HOME=$JAVA_HOME"
fi


##################################################
# Determine which JVM of version >1.6
# Try to use JAVA_HOME
##################################################
if [ "$JAVA" = "" -a "$JAVA_HOME" != "" ]
then
  if [ ! -z "$JAVACMD" ]
  then
     JAVA="$JAVACMD"
  else
    [ -x $JAVA_HOME/bin/jre -a ! -d $JAVA_HOME/bin/jre ] && JAVA=$JAVA_HOME/bin/jre
    [ -x $JAVA_HOME/bin/java -a ! -d $JAVA_HOME/bin/java ] && JAVA=$JAVA_HOME/bin/java
  fi
fi

JAVA_VERSION=`$JAVA -version 2>&1 | head -1 | sed 's/.*1\.\([0-9]\)\..*/\1/'`

if [ -z "$JAVA" ] || [ -z "$JAVA_VERSION" ] || [ $JAVA_VERSION -lt 5 ]
then
    echo "Cannot find a JRE or JDK. Please set JAVA_HOME to a >=1.5 JRE" 2>&2
    exit 1
fi


#####################################################
# See if JETTY_PORT is defined
#####################################################
if [ "$JETTY_PORT" != "" ]
then
  JAVA_OPTIONS="$JAVA_OPTIONS -Djetty.port=$JETTY_PORT"
fi


#####################################################
# Are we running on Windows? Could be, with Cygwin/NT.
#####################################################
case "`uname`" in
CYGWIN*) PATH_SEPARATOR=";";;
*) PATH_SEPARATOR=":";;
esac


#####################################################
# Add jetty properties to Java VM options.
#####################################################
JAVA_OPTIONS="$JAVA_OPTIONS -Djava.awt.headless=true"

#####################################################
# This is how the Artifactory server will be started
#####################################################
EXEC_FILE="$ARTIFACTORY_HOME/bin/artifactory.init"
echo "#!/bin/sh" > $EXEC_FILE
echo "JAVA_OPTIONS=\"$JAVA_OPTIONS\"" >> $EXEC_FILE
echo "JAVA_HOME=\"$JAVA_HOME\"" >> $EXEC_FILE
echo "ARTIFACTORY_HOME=\"$ARTIFACTORY_HOME\"" >> $EXEC_FILE
echo "export JAVA_OPTIONS JAVA_HOME ARTIFACTORY_HOME" >> $EXEC_FILE
echo "" >> $EXEC_FILE
cat $ARTIFACTORY_HOME/${ARTIFACTORY_START_FILE} >> $EXEC_FILE
if [ -n "$ARTIFACTORY_USER" ]; then
	chown ${ARTIFACTORY_USER} $EXEC_FILE
fi
chmod u+x $EXEC_FILE
RUN_CMD="$EXEC_FILE $CONFIGS"

#export JAVA_OPTIONS JAVA_HOME ARTIFACTORY_HOME
#RUN_CMD="source /tmp/artifactory.init && $ARTIFACTORY_HOME/${ARTIFACTORY_START_FILE} $CONFIGS"

#####################################################
# Comment these out after you're happy with what
# the script is doing.
#####################################################
#echo "ARTIFACTORY_HOME     =  $ARTIFACTORY_HOME"
#echo "JETTY_CONF           =  $JETTY_CONF"
#echo "ARTIFACTORY_USER           =  $ARTIFACTORY_USER"
#echo "ARTIFACTORY_RUN      =  $ARTIFACTORY_RUN"
#echo "ARTIFACTORY_PID      =  $ARTIFACTORY_PID"
#echo "ARTIFACTORY_CONSOLE  =  $ARTIFACTORY_CONSOLE"
#echo "JETTY_ARGS           =  $JETTY_ARGS"
#echo "CONFIGS              =  $CONFIGS"
#echo "JAVA_OPTIONS         =  $JAVA_OPTIONS"
#echo "JAVA                 =  $JAVA"
#echo "EXEC_FILE            =  $EXEC_FILE"
#echo "RUN_CMD              =  $RUN_CMD"


##################################################
# Do the action
##################################################
case "$ACTION" in
  start)
        echo "Starting Jetty: "
        echo "Artifactory home="$ARTIFACTORY_HOME

        if [ -f $ARTIFACTORY_PID ]
        then
            if [ "$(ps -p `cat $ARTIFACTORY_PID` | wc -l)" -gt 1 ]; then
				# process is still running
				echo "Already Running!"
				exit 1
			else
				# process not running, but PID file was not deleted
				echo "Artifactory was not stopped correctly. Removing old pid file"
				rm $ARTIFACTORY_PID
            fi
        fi

        echo "STARTED Jetty `date`" >> $ARTIFACTORY_CONSOLE

        ulimit -n 20000
        ulimit -s 128

        if [ -z "$ARTIFACTORY_USER" ]; then
            nohup sh -c "exec $RUN_CMD >>$ARTIFACTORY_CONSOLE 2>&1" >/dev/null &
        else
            nohup su - ${ARTIFACTORY_USER} --shell=/bin/sh -c "exec $RUN_CMD >>$ARTIFACTORY_CONSOLE 2>&1" >/dev/null &
        fi
        echo $! > $ARTIFACTORY_PID
        echo "Jetty running pid="`cat $ARTIFACTORY_PID`
        ;;

  stop)
        PID=`cat $ARTIFACTORY_PID 2>/dev/null`
        echo "Shutting down Jetty: $PID"
        kill $PID 2>/dev/null
        sleep 20
        kill -9 $PID 2>/dev/null
        rm -f $ARTIFACTORY_PID
        echo "STOPPED `date`" >>$ARTIFACTORY_CONSOLE
        ;;

  restart)
        $0 stop $*
        sleep 5
        $0 start $*
        ;;

  supervise)
       #
       # Under control of daemontools supervise monitor which
       # handles restarts and shutdowns via the svc program.
       #
         exec $RUN_CMD
         ;;

  run|demo)
        echo "Running Jetty: "

        if [ -f $ARTIFACTORY_PID ]
        then
            echo "Already Running!"
            exit 1
        fi

        exec $RUN_CMD
        ;;

  check)

   if [ -f $ARTIFACTORY_RUN/artifactory.pid ]
        then
            echo "Artifactory is running, on pid="`cat $ARTIFACTORY_RUN/artifactory.pid`
            echo ""
            exit 0
        fi

        echo "Checking arguments to Artifactory on Jetty: "
        echo "ARTIFACTORY_HOME     =  $ARTIFACTORY_HOME"
        echo "JETTY_CONF           =  $JETTY_CONF"
        echo "ARTIFACTORY_USER     =  $ARTIFACTORY_USER"
        echo "ARTIFACTORY_RUN      =  $ARTIFACTORY_RUN"
        echo "ARTIFACTORY_PID      =  $ARTIFACTORY_PID"
        echo "ARTIFACTORY_CONSOLE  =  $ARTIFACTORY_CONSOLE"
        echo "JETTY_PORT           =  $JETTY_PORT"
        echo "JETTY_ARGS           =  $JETTY_ARGS"
        echo "CONFIGS              =  $CONFIGS"
        echo "JAVA_OPTIONS         =  $JAVA_OPTIONS"
        echo "JAVA                 =  $JAVA"
        echo "CLASSPATH            =  $CLASSPATH"
        echo "RUN_CMD              =  $RUN_CMD"
        echo

        exit 1
        ;;

*)
        usage
        ;;
esac

exit 0
