#!/usr/bin/perl
# dwave/DYNAMiCS
use strict;
use POSIX qw(setsid);

my $DYNSYN_PIDFILE = "/tmp/dynsyn-current-pid";
my $INSTALLER_PID_CMD = "		\
	ps auxww 			|		\
	grep Installer.app	|		\
	grep -v grep		|		\
	awk '{print \$2}'
";

die("Usage: $0 /path/to/DynSyn DYNSYN_ARGUMENTS\n")
	unless @ARGV;

die("$0: ERROR: Installer.app is not running???\n")
	unless `$INSTALLER_PID_CMD`;

die("Dynsyn is already running. (Probably with another Installer.app).\n")
	if -f $DYNSYN_PIDFILE;

my $id = fork();
if($id == 1)
{
	die("$0: ERROR: Can't fork: $!\n");
}
if($id != 0)
{ 	# We are parent.
	printf("DynsynMon launched in the background...\n");
	printf("Every second we will test if Installer.app is still running,\n");
	printf("dynsyn will be stopped as soon as it's not.\n");
	exit();
}

#####
# This is the new process that will continue in the background.

POSIX::setsid(); # Become the new session leader.

# now that we are a background daemon, run DynSyn using argv.
system(@ARGV);

# sleep until Installer.app is finished...
while(chomp(my $installer_pid = `$INSTALLER_PID_CMD`))
{
	sleep 1;
}

my $ret = open(my $in, $DYNSYN_PIDFILE);
if($ret)
{
	my $dynsyn_pid = <$in>;
	close($in) or print("Can't close $DYNSYN_PIDFILE: $!\n");
	chomp($dynsyn_pid);
	kill(3, $dynsyn_pid); # 3 == SIGQUIT
	unlink($DYNSYN_PIDFILE);
}

exit(0);