#!/usr/bin/env perl

use strict;
use warnings;

use v5.16;
use feature qw<switch>;

use Config;
use Cwd qw<getcwd abs_path>;
use File::stat;

# report if the card says a firmware update is needed.
my $modver = `modinfo blackmagic | grep '^version: '`; chomp $modver;
if ($modver ne "") {
	$modver =~ s/^version: +//;
}

print "WARNING: Do not interrupt the firmware update. Once the update begins, it\n";
print "         must be allowed to complete.\n";
print "\n";
print "         When the firmware update completes, you will need to POWER DOWN\n";
print "         your Castus unit, and then POWER ON again, for the update to take\n";
print "         effect.\n";
print "\n";

print "Ready to update the firmware? (Type Y or yes to confirm): "; $|++;
my $ready = <STDIN>; chomp $ready;
if ($ready !~ /^[yY]/) {
	print "Update aborted, exiting\n";
	exit 0;
}

if ($modver =~ m/^12\./) {
	my $y = system("DesktopVideoUpdateTool -a -u");
	print "WARNING: Failure to update firmware\n" if ($y != 0);
}
elsif ($modver =~ m/^(9|10|11)\./) {
	my $i;
	my $count = `BlackmagicFirmwareUpdater status | wc -l`; # should be a reasonable way to determine highest number
	for ($i=0;$i < $count;$i++) {
		print "Updating card $i\n";
		my $x = system("BlackmagicFirmwareUpdater update $i");
		print "WARNING: Failure to update firmware\n" if ($x != 0);
		sleep 3; # chance for CTRL+C here
	}
}

print "Update complete. To finish the firmware update, power off your Castus unit,\n";
print "and then power it on again.\n";

sleep 3;

