#!/bin/bash
#
# ksmtuned     Kernel Samepage Merging (KSM) Tuning Daemon
#
# Author:      Dan Kenigsberg <danken@redhat.com>
#
# Copyright 2009 Red Hat, Inc. and/or its affiliates.
# Released under the GPL
#
# chkconfig: 345 85 15
# description: The KSM tuning daemon controls whether (and with what vigor) \
#              ksm should ksm search duplicated pages.
# processname: ksmtuned
# config: /etc/ksmtuned.conf
# pidfile: /var/run/ksmtuned.pid
#
### BEGIN INIT INFO
# Provides: ksmtuned
# Required-Start: $remote_fs
# Required-Stop: $remote_fs
# Should-Start:
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: tune the speed of ksm
# Description: The Kernel Samepage Merging control Daemon is a simple script
#   that controls whether (and with what vigor) should ksm search duplicated
#   memory pages.
#   needs testing and ironing. contact danken@redhat.com if something breaks.
### END INIT INFO

. /lib/lsb/init-functions

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

prog=ksmtuned
ksmtuned=/usr/sbin/ksmtuned
DESC="KSM control daemon"

pidfile=${PIDFILE-/var/run/ksmtune.pid}
RETVAL=0

test -x $ksmtuned || exit 0

# Include defaults if available
if [ -f /etc/default/$prog ] ; then
        . /etc/default/$prog
fi

if [ "$START" != "yes" ]; then
        exit 0
fi

start() {

    [ -d /sys/kernel/mm/ksm/ ] || exit 0;

    log_daemon_msg "Starting $DESC" $prog
    pid=$( pidofproc -p ${pidfile} $ksmtuned )
    if [ -n "$pid" ] ; then
	log_begin_msg "Already running."
	log_end_msg 0
	exit 0
    fi

    start-stop-daemon --start --quiet --pidfile=${pidfile} --exec $ksmtuned
    RETVAL=$?
    log_end_msg $RETVAL
}

stop() {
    log_daemon_msg "Stopping $DESC" $prog
    start-stop-daemon --stop --quiet --pidfile ${pidfile}
    RETVAL=$?
    log_end_msg $RETVAL
}

restart() {
    stop
    start
}

case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
	pidofproc -p ${pidfile} $ksmtuned >/dev/null
 	RETVAL=$?
	if [ $RETVAL -eq 0 ]; then
	    log_success_msg "$DESC is running."
	else
	    log_failure_msg "$DESC is not running."
	fi
	;;
  restart|force-reload)
	restart
	;;
  reload)
	pid=$( pidofproc -p ${pidfile} $ksmtuned )
	if [ -n "$pid" ] ; then
            kill -SIGUSR1 $pid
            RETVAL=$?
	else
	    log_failure_msg "$DESC is not running."
 	fi
        ;;
  *)
	echo $"Usage: $prog {start|stop|restart|force-reload|status|reload|help}"
	RETVAL=2
esac

exit $RETVAL
