#!/bin/bash
#
# ksenosd        Ksenos Server startup script
#
# chkconfig: - 85 15
# description: Ksenos DVR Server
# processname: ksenosd
# pidfile: /dev/shm/DVR-ksenos
#
### BEGIN INIT INFO
# Provides: ksenos-prime
# Required-Start: $local_fs $remote_fs $network $named
# Required-Stop: $local_fs $remote_fs $network
# Short-Description: start and stop Ksenos DVR
# Description: Ksekos DVR Server
### END INIT INFO

# Source function library.
. /etc/rc.d/init.d/functions

ksenosd=ksenosd
pidfile=/dev/shm/DVR-ksenos
STOP_TIMEOUT=10
LFILE=~ksenos/.dvr/license

function licensefromdmi() {
	if [ ! -f /usr/sbin/dmidecode ]; then
        	return 2
	fi

	if [ "$(dmidecode -s system-manufacturer)" != "Ksenos" ]; then
		return 1
	fi

	pkey=$(dmidecode -t 11 | grep "String 1:" | cut -d : -f 2- | tr -d ' ')
	act=$(dmidecode -t 12 | grep "Option 1:" | cut -d : -f 2- | tr -d ' ')

	if egrep -q '^([A-Z0-9]{4}-){6}' <<< "$pkey" ; then
		if egrep -q '^[A-Z0-9]{30}' <<< "$act" ; then
			echo "ksenos $pkey" > "$1"
			echo "ksenos_act $act" >> "$1"
			chown ksenos:ksenos "$1"
		fi
	fi
}

start() {
	if [ ! -f "$LFILE" ] ; then
		licensefromdmi "$LFILE"
	fi

        echo -n $"Starting $prog: "
        daemon --user ksenos --pidfile=${pidfile} $ksenosd -D $OPTIONS
        RETVAL=$?
        echo
        # [ $RETVAL = 0 ] && touch ${lockfile}
        return $RETVAL
}

stop() {
	echo -n $"Stopping $prog: "
	killproc -p ${pidfile} -d ${STOP_TIMEOUT} $ksenosd
	RETVAL=$?
	echo
	[ $RETVAL = 0 ] && rm -f ${lockfile} ${pidfile}
}

reload() {
	false
}

# See how we were called.
case "$1" in
  start)
	start
	;;
  stop)
	stop
	;;
  status)
        status -p ${pidfile} $ksenosd
	RETVAL=$?
	;;
  restart)
	stop
	start
	;;
  *)
	echo $"Usage: $prog {start|stop|restart|status}"
	RETVAL=2
esac

exit $RETVAL
