#!/bin/sh

# Generated by pleaserun and then modified as needed

### BEGIN INIT INFO
# Provides:          app-search
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description:
# Description:       app-search
### END INIT INFO

PATH=/sbin:/usr/sbin:/bin:/usr/bin
export PATH

name=app-search
program=/usr/share/app-search/bin/app-search
log_directory="/var/log/$name"
log_file="$log_directory/init.log"
args=''
pidfile="/var/run/$name.pid"
user="app-search"
group="app-search"
chroot="/"
chdir="/usr/share/app-search"

trace() {
  logger -t "/etc/init.d/app-search" "$@"
}

emit() {
  trace "$@"
  echo "$@"
}

start() {
  chroot --userspec "$user":"$group" "$chroot" sh -c "
    cd \"$chdir\"
    exec \"$program\" $args
  " >> $log_file 2>&1 &

  # Generate the pidfile from here. If we instead made the forked process
  # generate it there will be a race condition between the pidfile writing
  # and a process possibly asking for status.
  echo $! > $pidfile

  emit "$name started"
  return 0
}

stop() {
  # Try a few times to kill TERM the program
  if status ; then
    pid=$(cat "$pidfile")
    trace "Killing $name (pid $pid) with SIGTERM"
    kill -TERM "$pid"
    # Wait 15s for it to exit.
    for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ; do
      trace "Waiting $name (pid $pid) to die..."
      status || break
      sleep 1
    done
    if status ; then
      emit "$name stop failed; still running."
    else
      emit "$name stopped."
    fi
  fi
}

status() {
  if [ -f "$pidfile" ] ; then
    pid=$(cat "$pidfile")
    if ps -p "$pid" > /dev/null 2> /dev/null ; then
      # process by this pid is running.
      # It may not be our pid, but that's what you get with just pidfiles.
      return 0
    else
      return 2 # program is dead but pid file exists
    fi
  else
    return 3 # program is not running
  fi
}

case "$1" in
  start|stop|restart)
    trace "Attempting '$1' on app-search"
    ;;
esac

case "$1" in
  start)
    status
    code=$?
    if [ $code -eq 0 ]; then
      emit "$name is already running"
      exit $code
    else
      start
      exit $?
    fi
    ;;
  stop) stop ;;
  status)
    status
    code=$?
    if [ $code -eq 0 ] ; then
      emit "$name is running"
    else
      emit "$name is not running"
    fi
    exit $code
    ;;
  restart)
    stop && start
    ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart}" >&2
    exit 3
  ;;
esac

exit $?
