#!/usr/bin/perl
# Decklink 12.x desktop video helper service.
# The SDK will NOT enumerate any cards until this process
# is resident... or at least run once after startup. The
# SDK doesn't seem to require that this service keep running
# after that.
# 
# If both the Black Magic Design desktop GUI and Castus software
# are not showing any cards or inputs or outputs, start this
# service and try again.
# 
# To avoid problems, this script will not do anything if your
# Decklink drivers are not 12.x

use Time::HiRes qw( usleep );

my $how = shift(@ARGV);
my $exe = undef;
my $pid;
my $t;

$t = "/usr/lib64/blackmagic/DesktopVideo/DesktopVideoHelper";
$exe = $t if (!defined($exe) && -x $t);

$t = "/usr/lib/blackmagic/DesktopVideo/DesktopVideoHelper";
$exe = $t if (!defined($exe) && -x $t);

exit 0 unless defined($exe);

if ($how eq "start") {
	$pid = `pidof '$exe'`; chomp $pid;

	if ($pid ne "") {
		# it's is already running
		exit 0;
	}

	# make sure Decklink 12.x drivers are involved first.
	# We at Castus allow our clients to downgrade if necessary,
	# also not every client will have 12.x drivers quite yet.
	$t = `modinfo blackmagic | grep version:`; chomp $t;
	$t =~ s/^version:[ \t]+//;
	exit 0 unless $t =~ m/^12\./i;

	# run, redirect blather elsewhere and STDERR to log
	open(STDIN,"</dev/null");
	open(STDERR,">/dev/null");
	open(STDOUT,">/dev/null");

	my $p = fork;
	if ($p == 0) {
		exec($exe);
		exit 0;
	}
}
elsif ($how eq "stop") {
	my $patience;
	$pid = `pidof '$exe'`; chomp $pid;
	if ($pid > 0) {
		system("kill -s TERM $pid"); $patience = 5000;
		do { usleep(1000); } while ( $patience-- > 0 && -e "/proc/$pid");
		system("kill -s KILL $pid") if ( -e "/proc/$pid" );
	}
}
elsif ($how eq "status") {
	$pid = `pidof '$exe'`; chomp $pid;
	if ($pid ne "") {
		print "running\n";
		exit 0;
	}
	else {
		print "stopped\n";
		exit 1;
	}
}

