#!/bin/sh

### BEGIN REDHAT INFO
# chkconfig: 2345 99 20
# description: Neo4j Graph Database server
### END REDHAT INFO
### BEGIN INIT INFO
# Provides:          neo4j
# Required-Start:    $remote_fs $syslog $network
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Neo4j Graph Database server
# Description:       Neo4j is a Graph Database, which is a compelling
#                    alternative to an RDBMS. https://neo4j.com
### END INIT INFO

# Copyright (c) 2002-2023 "Neo4j"
# Neo4j Sweden AB [https://neo4j.com]
#
# This file is part of Neo4j.
#
# Neo4j is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

PATH=/sbin:/usr/sbin:/bin:/usr/bin
NAME=neo4j
DAEMON=/usr/bin/${NAME}
PIDDIR=/var/run/${NAME}
PIDFILE=${PIDDIR}/neo4j.pid
SCRIPTNAME=/etc/init.d/${NAME}

[ -x "$DAEMON" ] || exit 0
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
[ -n "${NEO_USER}" ] || NEO_USER=$NAME

# Debian distros and SUSE
has_lsb_init()
{
  test -f "/lib/lsb/init-functions" && [ $(grep -c status_of_proc /lib/lsb/init-functions) -gt 0 ] && [ $(grep -c start-stop-daemon /lib/lsb/init-functions) -gt 0 ]
}

# RedHat/Centos distros
has_init()
{
  test -f "/etc/init.d/functions"
}


if has_lsb_init ; then
  . /lib/lsb/init-functions
elif has_init ; then
  . /etc/init.d/functions
else
  echo "Error: your platform is not supported by ${NAME}" >&2
  exit 1
fi

do_start()
{
  do_ulimit
  [ -d "${PIDDIR}" ] || mkdir -p "${PIDDIR}"
  chown "${NEO_USER}:" "${PIDDIR}"

  if has_lsb_init ; then
    start-stop-daemon --chuid ${NEO_USER} --start --quiet --oknodo --pidfile ${PIDFILE} --exec ${DAEMON} -- start
  else
    daemon --user="${NEO_USER}" --pidfile="${PIDFILE}" "${DAEMON} start > /dev/null 2>&1 &"
  fi
}

do_stop()
{
  ${DAEMON} stop
}

do_status()
{
  if has_lsb_init ; then
    status_of_proc -p "${PIDFILE}" "${DAEMON}" "${NAME}"
  else
    status -p "${PIDFILE}" "${NAME}"
  fi
}

do_ulimit()
{
  if [ -n "${NEO4J_ULIMIT_NOFILE}" ]; then
    ulimit -n "${NEO4J_ULIMIT_NOFILE}"
  fi
}

case "$1" in
  start)
    do_start
    ;;
  stop)
    do_stop
    ;;
  status)
    do_status
    ;;
  restart|force-reload)
    do_stop && do_start
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
esac
