#! /bin/sh
#
# Name: bootcount
# Author: SpinetiX S.A.
# Copyright: 2007 SpinetiX S.A.
# License: 2007 (c) SpinetiX S.A. This file is licensed
#          under the terms of the GNU General Public License version 2.
#          This program is licensed "as is" without any warranty of any
#          kind, whether express or implied.
#
# Copyright 1999-2003 MontaVista Software, Inc.
# Copyright 2002, 2003, 2004 Sony Corporation
# Copyright 2002, 2003, 2004 Matsushita Electric Industrial Co., Ltd.
#
### BEGIN INIT INFO
# Required-Start:
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:
# Short-Description: resets the bootcount
# Description: resest the bootcount after waiting a preconfigured delay in the background.
### END INIT INFO
# chkconfig: 235 99 99

#
# To externally modify the bootcount call this script with the 'noreset'
# argument *before* modifying the bootcount.
#

# Init script information
INIT_NAME=bootcount
DESC="bootcount reset"

# Load init script configuration
[ -f /etc/default/$INIT_NAME ] && . /etc/default/$INIT_NAME

# Source the init script functions
. /etc/init.d/init-functions

# Source spxsysconf functions
. /etc/spinetix/init-functions

# Verify proc file exists
[ "$1" = "status" ] && NFOUND=4 || NFOUND=5
test -f $BOOTCOUNT || exit $NFOUND

start() {
	local RET ERROR=
	
	log_status_msg "Starting $DESC: " -n
	log_status_msg "delay $DELAY secs" -n
	(sleep $DELAY && [ ! -f $BOOTCOUNT_NORESET ] && echo 0 > $BOOTCOUNT) &
	RET=$?
	if [ $RET -eq 0 ]; then
		log_success_msg ". "
	else
		log_failure_msg " failed ($RET: $ERROR)."
		return 1
	fi
	
	log_status_msg ""
	return 0
}

stop() {
	local RET ERROR=

	log_status_msg "Stopping $DESC: " -n
	if [ ! -f $BOOTCOUNT_NORESET ]; then
	    echo 0 > $BOOTCOUNT
	    rm -f $BOOTCOUNT_NORESET
	    RET=$?
	else
	    RET=0
	fi
	if [ $RET -eq 0 ]; then
		log_success_msg ". "
	else
		log_failure_msg "failed ($RET: $ERROR). " -n
		return 1
	fi

	log_status_msg ""
	return 0
}

status() {
	local RET

	COUNT=`cat $BOOTCOUNT`
	echo -n "current boot count is $COUNT"
	if [ ! -f $BOOTCOUNT_NORESET ]; then
	    echo " (will reset)"
	else
	    echo " (will not reset)"
	fi
	RET=$?

	return $RET
}

parse() {
	case "$1" in
		start)
			start
			return $?
	;;
		stop)
			stop
			return $?
	;;
		noreset)
			touch $BOOTCOUNT_NORESET
			return $?
	;;
		status)
			status
			return $?
	;;
		*)
			echo "Usage: $INIT_NAME " \
			"{start|stop|noreset|status}" >&2
	;;
	esac
	
	return 1
}

parse $@
