#!/bin/bash
#
# kcare        KernelCare startup
#
# chkconfig: 2345 15 95
# description: Loads kernelcare patches on startup

### BEGIN INIT INFO
# Provides:          kcare
# Required-Start:    $remote_fs $syslog $network
# Required-Stop:     $remote_fs $syslog $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: KernelCare startup
# Description:       Loads kernelcare patches on startup
### END INIT INFO

# Source function library.
if [ -f /etc/rc.d/init.d/functions ]; then
  # shellcheck source=/dev/null
  . /etc/rc.d/init.d/functions
elif [ -f /lib/lsb/init-functions ]; then
  # shellcheck source=/dev/null
  . /lib/lsb/init-functions
else
  echo "Could not find functions file, your system may be broken"
  exit 1
fi

# shellcheck disable=SC2034  # Variable is not a mistake
prog="kcare"
bin="/usr/bin/kcarectl"
start() {
    $bin --smart-update &
    touch /var/lock/subsys/kcare
}

stop() {
    # Record shutdown timestamp for anomaly detection (crash vs proper shutdown).
    date +%s > /var/cache/kcare/stopped.at
    # KPT-5409: unload patches only on shutdown/reboot (runlevels 0 and 6),
    # not on regular service stop/restart. kcare_load() handles re-patching
    # atomically so restarting the service does not require an unload cycle.
    rl=$(runlevel 2>/dev/null | awk '{print $2}') || true
    if [[ "$rl" == "0" ]] || [[ "$rl" == "6" ]]; then
        $bin --unload > /dev/null
    fi
    rm -rf /var/lock/subsys/kcare
    # Ordinary reboot will lead to the service stopping and we
    # can delete smart-update lock file.
    rm -rf /var/cache/kcare/.kcareprev.lock
}

restart() {
    stop
    start
}

# See how we were called.
case "$1" in
  start)
      start
      ;;
  stop)
      stop
      ;;
  restart|reload|force-reload)
      restart
      ;;
  status)
      $bin --info
      RETVAL=$?
      ;;
  *)
        echo $"Usage: $0 {start|stop|status|restart|reload}"
        exit 1
esac

exit "${RETVAL:-$?}"
