#!/usr/bin/perl -w
#
# Creates a sysvinit file from a metainit description.
#

#
# Note that we’d like to adhere the LSB, so see
# http://refspecs.freestandards.org/LSB_2.1.0/LSB-generic/LSB-generic/iniscrptact.html
#

use MetaInit::Parse;

$filename = shift || die "Useage: $0 <filename>\n";
my $output = shift;

# Parse the metainit in
%initparams = %{MetaInit::Parse::parse({ filename => $filename })};

if ($output) {
    open(STDOUT,'>',$output) or die "Can't open '$output': $!";
}

# Print the "dynamic" part of the initscript

my $rl_start = join " ", @{$initparams{"Start-Levels"}};
my $rl_stop  = join " ", @{$initparams{"Stop-Levels"}};

print << "EOF";
#! /bin/sh
#
# This a generated file. DO NOT EDIT THIS FILE!
# If you want to modify how this file works, please
# modify $filename and re-run update-metainit.
#
# If you are sure that you want to modify this file,
# remove this comment, and update-metainit will not override
# this script any more.
#
### BEGIN INIT INFO
# Provides:          $initparams{"Name"}
# Default-Start:     $rl_start
# Default-Stop:      $rl_stop
# Short-Description: $initparams{"Short-Description"}
EOF

print "# Required-Start:   " . join(" ",@{$initparams{"Required-Start"}}) . "\n";
print "# Required-Stop:     " . join(" ",@{$initparams{"Required-Stop"}}) . "\n";
print "# Description:       ";
print join("\n#                    ",split("\n",$initparams{"Description"})). "\n";
print "\n";

# prevent quoted strings from breaking the generated script:

my %quoted_initparams;

while (my ($k, $v) = each %initparams){
    $quoted_initparams{$k} = quotemeta ($v || '');
}

print << "EOF"
### END INIT INFO

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC=$quoted_initparams{"Short-Description"}
NAME=$quoted_initparams{"Name"}
DAEMON=$initparams{"Path"}
BASENAME=$initparams{"Basename"}
DAEMON_ARGS=$quoted_initparams{"Args"}
PIDFILE=/var/run/\$NAME.pid
SCRIPTNAME=/etc/init.d/\$NAME
EOF
;

# ... and the rest of the initscript, that is identical for all
# metainit-created scripts.
print << 'EOF'
# Exit if the package is not installed
[ -x "$DAEMON" ] || exit 5

# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh

# Define LSB log_* functions.
# Depend on lsb-base (>= 3.0-6) to ensure that this file is present.
. /lib/lsb/init-functions

#
# Function that starts the daemon/service
#
do_start()
{
EOF
;

if($initparams{"Prestart-Hook"}) {
    print "\t" . join("\n\t",split("\n",$initparams{"Prestart-Hook"}));
    print "\n";
}

print << 'EOF'
	start-stop-daemon --start --oknodo --background --quiet --make-pidfile --pidfile $PIDFILE --exec $DAEMON -- \
		$DAEMON_ARGS || return 1
}

#
# Function that stops the daemon/service
#
do_stop()
{
	start-stop-daemon --stop --oknodo --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $BASENAME
	RETVAL="$?"

	rm -f $PIDFILE

	return $RETVAL
EOF
;

if($initparams{"Poststop-Hook"}) {
    print "\t" . join("\n\t",split("\n",$initparams{"Poststop-Hook"}));
    print "\n";
}

print << 'EOF';
	return "$RETVAL"
}

#
# Function that sends a SIGHUP to the daemon/service
#
do_reload() {
	start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
	return 0
}

case "$1" in
  start)
	[ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
	do_start
    log_end_msg $?
	;;
  stop)
	[ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
	do_stop
    log_end_msg $?
	;;
  #reload|force-reload)
	#
	# If do_reload() is not implemented then leave this commented out
	# and leave 'force-reload' as an alias for 'restart'.
	#
	#log_daemon_msg "Reloading $DESC" "$NAME"
	#do_reload
	#log_end_msg $?
	#;;
  restart|force-reload)
	#
	# If the "reload" option is implemented then remove the
	# 'force-reload' alias
	#
	log_daemon_msg "Restarting $DESC" "$NAME"
	do_stop
	case "$?" in
	  0)
		do_start
        log_end_msg "$?"
		;;
	  *)
	  	# Failed to stop
		log_end_msg 1
		;;
	esac
	;;
  *)
	#echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac
EOF

if ($output) {
    close STDOUT;
    chmod 0755, $output or die "Can't change permissions for '$output': $!";
}

# vim: ts=4:sw=4:expandtab
