#
# Move to Server
#
# Monitor the debug and release folders for a new binary.
# If found, 
#	1 Read the .ino file to find the current version string.
#	2 Rename the .bin to include the version string.
#	3 Move it to the server.
#
# Searches .ino file for: const String MyVer = "SmartSwitch v1.02.24";
#
use strict;
use warnings;

######################  Configuration   ###########################
#
# Target Server Path
#
my $ServerPath = "\\\\server1\\web\\mbed\\ESPbin";

# Sleep Time between checks
#
my $SleepTime = 5;

# Verbose mode
#	0 = off
#	1 = highlights
#	2 = detailed
#
my $Verbose = 1;

#####################

my $continue = 1;

$SIG{INT}  = sub { $continue = 0; };
$SIG{TERM} = sub { $continue = 0; };

do {
	printf("\n") if ($Verbose > 1);
	printf("MoveToServer check at %s\n", scalar localtime()) if ($Verbose == 1);
	chdir "../Firmware";
	Process();
	Pause($SleepTime);
} while ($continue);

exit;

####################################################################


sub Process {
	my $slnFile = "";

	my @files = glob("*.sln");
	foreach (@files) {
		$slnFile = $_;
		printf("  Found: %s\n", $slnFile) if ($Verbose > 1);
	}

	if ($slnFile eq "") {
		printf("  *** No Solution Files found ...\n") if ($Verbose == 1);
		return;
	}

	my $inoFile = $slnFile;
	$inoFile =~ s/(.*)\.sln/$1\.ino/;
	if (!-e $inoFile) {
		printf("  *** %s not found ...\n", $inoFile) if ($Verbose == 1);
		return;
	}
	printf("  Search %s\n", $inoFile) if ($Verbose > 1);
	my $verString = GetVerString($inoFile);
	if ($verString eq "") {
		printf("    *** No Version string in %s ...\n", $inoFile) if ($Verbose == 1);
		return;
	}
	printf("    Version '%s'\n", $verString) if ($Verbose > 1);

	my $targBin = $slnFile;
	$targBin =~ s/(.*)\.sln/$1\.bin/;
	printf("  Target Bin file is %s\n", $targBin) if ($Verbose > 1);

	my @Folders = qw(Debug Release);
	foreach my $f (@Folders) {
		printf("    Scanning %s\n", $f) if ($Verbose > 1);
		my $tF = "$f\\$targBin";
		if (-e $tF) {
			printf("    Processing %s\n", $tF) if ($Verbose > 1);
			my $srvrFile = "$ServerPath\\$verString.bin";
			my $cmd = sprintf("move /Y \"%s\" \"%s\"", $tF, $srvrFile);
			printf("      > %s\n", $cmd);
			`$cmd`;
		}
	}
}


sub Pause {
	my $dly = shift;
	my $count = 0;
	
	while ($count++ < $dly && $continue) {
		sleep(1);
	}
}

sub GetVerString {
	my $iF = shift;
	my $ver = "";
	
	open(IF, "<$iF") || return $ver;
	#const String MyVer = "SmartSwitch v1.02.24";
	while (<IF>) {
		if (/String MyVer = \"(.*)\"/) {
			$ver = $1;
			last;
			#close IF;
			#return $ver;
		}
	}
	close IF;
	return $ver;
}
