#!/usr/bin/perl

#
# ISPConfig runs tasks on cron, but cron only runs every minute.
# If that takes too long to change the configs of the hosts... this daemon might help.
#  
# Add this script a boot script /etc/init.d/boot.local or /etc/rc.local or a systemd service.
#
# Usage:
# - /usr/local/ispconfig/server/scripts/start_server.pl --start (Start)
# - /usr/local/ispconfig/server/scripts/start_server.pl --stop (Stop)
#
# You can then disable the regular cronjob calling /usr/local/ispconfig/server/server.sh
#
# Systemd example:
# past the code below to `/lib/systemd/system/ispconfig-runner.service`
# then run  `systemctl daemon-reload` and `systemctl enable ispconfig-runner`
# And finally `service ispconfig-runner start`
#
#===
# [Unit]
# Description=Start an ISPconfig task runner server
# After=network.target
#
# [Service]
# Type=forking
# PIDFile=/var/run/ispdaemon.pid
# User=root
# Group=root
# WorkingDirectory=/usr/local/ispconfig
# ExecStart=/usr/local/ispconfig/server/scripts/start_server.pl --start
#
# Restart=on-failure
#
# [Install]
# WantedBy=multi-user.target
#===

use Getopt::Long;
use POSIX qw(setsid);


my $start_daemon = 0;
my $stop_daemon  = 0;

GetOptions ('start' => \$start_daemon, 'stop' => \$stop_daemon ) or ( &help );


my $work_dir     = '/usr/local/ispconfig/server/';
my $child_STDOUT = '/var/log/ispconfig/ispdaemon.log';
my $pid_file     = '/var/run/ispdaemon.pid';
my $exec_command = '/usr/bin/php -q /usr/local/ispconfig/server/server.php';



if ($start_daemon) {

	my $PID = &daemonize();
	open PID, ">$pid_file" or die "Can't write to $pid_file: $!";
	print PID "$PID\n"; close PID;

	while (1) {
		print "Start Daemon ispconfig\n";
		`$exec_command`;
		sleep(20);
	}

}

if ($stop_daemon) {

	if(-e $child_STDOUT){
		unlink $child_STDOUT;
	}

	if (-e $pid_file){ 
		chomp(my $pid2 = `cat $pid_file`);
		`kill -9 $pid2`;
		unlink $pid_file;
	}

}



sub daemonize {
	chdir $work_dir or die "Can't chdir to $work_dir : $!";
	umask 0022;
	open STDIN, '/dev/null'  or die "Can't read /dev/null: $!";

	#All print statments will now be sent to our log file
	open STDOUT, ">>$child_STDOUT" or die "Can't write to $child_STDOUT: $!";

	#All error messages will now be sent to our log file
	open STDERR, ">>$child_STDOUT" or die "Can't write to $child_STDOUT: $!";


	defined(my $pid = fork) or die "Can't fork: $!";
	exit if $pid;
	setsid() or die "Can't start a new session: $!";
	my $PROC = $$;
	return $PROC;
}


sub help {
	print "Usage $0 --start => start daemon ispconfig\n";
	print "Usage $0 --stop  => stop daemon ispconfig\n";
}

