#!/usr/bin/perl
#
# Castus update script for Black Magic Design Decklink Video cards

my $instpath = "/mnt/main/tv/install";
my $instparent = "/mnt/main/tv";
my $src_zip;

# don't allow shell-unsafe chars
die "ZIP filename has invalid chars. Please rename." if $src_zip =~ m/[^a-zA-Z0-9 \.-]/;

die "$instparent does not exist" unless -d $instparent;

die "You must type in the name of the zip archive" if @ARGV < 1;
$src_zip = shift @ARGV;

die "$src_zip does not exist" unless -f $src_zip;

# HACK: Many of our older installs don't have 'realpath' Arrrrgh
my $has_realpath = 0;
$has_realpath = 1 if -x "/usr/bin/realpath";

# top dir?
my $pwd = `pwd`; chomp $pwd;

# might be a relative path. make absolute
if ($has_realpath) {
	$n_zip = `realpath $src_zip`;
	chomp $n_zip;
}
else {
	# all we can offer is "if it's a file, relative to this path" and "if starts with slash, absolute path"
	$n_zip = undef;
	$n_zip = $src_zip if substr($src_zip,0,1) eq '/'; # one slash at start: absolute
	$n_zip = $pwd.'/'.$src_zip if index($src_zip,'/') < 0;	# no slashes: relative to here
}
die "Cannot resolve absolute path of $src_zip" if $n_zip eq '';
die "Zip filename or path has invalid character \\ or '" if $n_zip =~ m/['\\]/;
$src_zip = $n_zip;
print "Will use $src_zip\n";

# install path must exist
chdir $instparent || die "Cannot enter $instparent";

system "rm -Rf install";
mkdir "install";

chdir $instpath || die "Cannot enter $instpath";

# now that we're in the install path, clean out previous updates, unpack zip archive.
# add -j to ignore directories and -o to always overwrite (to avoid prompts about existing files)
system("rm -Rf binary?? *.tar *.tar.sha1 *.pl *.sh") == 0 || die "Failed to clear previous files";
system("unzip -j -o '$src_zip'") == 0 || die "Failed to unzip package";

# look for blackmagic-dv-update-YYYYMMDD-HHMMSS.pl
$n=`ls blackmagic-dv-update-????????-??????.pl 2>/dev/null`; chomp $n;
die "Unable to locate update script" if $n eq '';
die "Update script not executable" unless ( -f $n && -x $n && !( -l $n ) ); # file, executable, not a symlink
die "Update script has invalid filename" if $n =~ m/[^a-zA-Z0-9 \.-]/;

# NTS: The main update script has to contend with "my $_ = ..." added sometime 2019.
#      The DV scripts written by Jon do not do that, no need to check for it.

# run it!
system("./$n") == 0 || die "Update script failed";

