#!/bin/sh
### BEGIN INIT INFO
# Provides:          retain
# Required-Start:    $remote_fs $syslog $network lxe
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: CRI shim to persist containers
# Description:       CRI shim to persist containers
### END INIT INFO

. /lib/lsb/init-functions

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

name=retain
program=/usr/bin/retain
pidfile="/run/$name/$name.pid"
user="root"
group="root"
chroot="/"
chdir="/var/lib/retain"


# If this is set to 1, then when `stop` is called, if the process has
# not exited within a reasonable time, SIGKILL will be sent next.
# The default behavior is to simply log a message "program stop failed; still running"
KILL_ON_STOP_TIMEOUT=1

[ -z "$nice" ] && nice=0

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

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

start() {
  mkdir -p /run/$name && chown $user:$group /run/$name
  mkdir -p /var/log/$name && chown $user:$group /var/log/$name



  # Run the program!
  chroot --userspec "$user":"$group" "$chroot" sh -c "
    cd \"$chdir\"
    exec \"$program\"
  " >/dev/null 2>&1 &

  # Generate the pidfile from here.
  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 for it to exit.
    for i in 1 2 3 4 5 ; do
      trace "Waiting $name (pid $pid) to die..."
      status || break
      sleep 1
    done
    if status ; then
      if [ "$KILL_ON_STOP_TIMEOUT" -eq 1 ] ; then
        trace "Timeout reached. Killing $name (pid $pid) with SIGKILL.  This may result in data loss."
        kill -KILL "$pid"
        emit "$name killed with SIGKILL."
      else
        emit "$name stop failed; still running."
      fi
    else
      emit "$name stopped."
    fi
    rm -f "$pidfile"
  fi
}

status() {
  if [ -f "$pidfile" ] ; then
    pid=$(cat "$pidfile")
    if ps -p "$pid" > /dev/null 2> /dev/null ; then
      return 0 # process by this pid is running.
    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|force-reload)
    trace "Attempting '$1' on $name"
    ;;
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|force-reload) stop && start ;;
  *)
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
  ;;
esac

exit $?
