#!/bin/bash
#
# partimaged	This shell script starts partimage server
#
# chkconfig:	345 56 44
# description:	This scripts starts partimage server \
#		which allow to get partimage partition \
#		images over network

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

# Get network config
. /etc/sysconfig/network

# Set defaults
PORT=4025
DESTDIR="/var/spool/partimage"

# Get service config
[ -f /etc/sysconfig/partimaged ] && . /etc/sysconfig/partimaged

# Check that networking is up.
if is_yes "${NETWORKING}"; then
	if [ ! -f /var/lock/subsys/network ]; then
		msg_network_down partimaged
		exit 1
	fi
else
        exit 0
fi


# See how we were called.
case "$1" in
  init)
	umask 077
        echo "Generating private key: /etc/partimaged/partimaged.key"
        openssl genrsa -out /etc/partimaged/partimaged.key 1024 \
		&& chown partimag:root /etc/partimaged/partimaged.key \
		&& chmod 600 /etc/partimaged/partimaged.key

        echo "Generating certificate request: /etc/partimaged/partimaged.csr"
        openssl req -new -x509 -outform PEM -out /etc/partimaged/partimaged.csr \
		-key /etc/partimaged/partimaged.key -config /etc/partimaged/partimaged.cnf \
		&& chmod 600 /etc/partimaged/partimaged.csr

        echo "Generating self-signed certificate: /etc/partimaged/partimaged.cert"
        openssl x509 -in /etc/partimaged/partimaged.csr -out /etc/partimaged/partimaged.cert \
		-signkey /etc/partimaged/partimaged.key && chmod 644 /etc/partimaged/partimaged.cert
	;;
  start)
	if [ ! -f /var/lock/subsys/partimaged ]; then
		msg_starting partimaged
		OPTIONS="-D"
		[ -n "$PORT" ] && OPTIONS="$OPTIONS --port $PORT"
		[ -n "$DEBUGLEVEL" ] && OPTIONS="$OPTIONS --debug $DEBUGLEVEL"
		[ -n "$DESTDIR" ] && OPTIONS="$OPTIONS --dest $DESTDIR"
		[ -n "$CHROOTDIR" ] && OPTIONS="$OPTIONS --chroot $CHROOTDIR"
		daemon partimaged $OPTIONS
		RETVAL=$?
		[ $RETVAL -eq 0 ] && touch /var/lock/subsys/partimaged
	else
		msg_already_running partimaged
	fi
	;;
  stop)
	if [ -f /var/lock/subsys/partimaged ]; then
		msg_stopping partimaged
		killproc partimaged
		rm -f /var/lock/subsys/partimaged >/dev/null 2>&1
	else
		msg_not_running partimaged
	fi
	;;
  status)
	status partimaged
	exit $?
	;;
  restart|force-reload)
	$0 stop
	$0 start
	exit $?
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status}"
	exit 3
esac

exit $RETVAL
