#!/usr/bin/perl -w

#
#  ORI Board serial number and LTC eeprom programming.
#

use strict;


#
# Set up variables.

printf "\n";

my $Serial_MSC = 0;
my $Serial_PI =  0;

if (@ARGV == 1)
{
	$Serial_MSC = $ARGV[0];
	$Serial_PI = $ARGV[0];
}
elsif (@ARGV == 2)
{
	$Serial_MSC = $ARGV[0];
	$Serial_PI = $ARGV[1];
}
else
{
	printf "Usage:  set_serial.pl <MSC serial lowest byte> [<PI serial lowest byte>]"
}

#
# Write least significant parts of IDs.
my $Res_MSC = qx(pc2tp -i2c 0xAE 0x00 $Serial_MSC);
my $Res_PI = qx(pc2tp -i2c 0xAE 0x10 $Serial_MSC);

my $Res_CheckMSC = qx(pc2tp -i2c 0xAF 0x00 0);

#
# Analyse output of the form: Access to PCI device: /dev/psi/vendor/0x1172/device/0x0005/0/base0
#                             i2c access, device=0xaf, addr=0x10, data_in=0x0, data_out=0x11
#                             Number of pings, reads, writes : 0, 12, 126

my @OutputLines = split(/\n/, $Res_CheckMSC);
my $Line = $OutputLines[@OutputLines - 2];

my @OutputParts = split(/ +|\t +|, |=/, $Line);
my $Serial_MSC_read = $OutputParts[9];

my $Res_CheckPI = qx(pc2tp -i2c 0xAF 0x10 0);

#
# Analyse output of the form: Access to PCI device: /dev/psi/vendor/0x1172/device/0x0005/0/base0
#                             i2c access, device=0xaf, addr=0x10, data_in=0x0, data_out=0x11
#                             Number of pings, reads, writes : 0, 12, 126

@OutputLines = split(/\n/, $Res_CheckPI);
$Line = $OutputLines[@OutputLines - 2];

@OutputParts = split(/ +|\t +|, |=/, $Line);
my $Serial_PI_read = $OutputParts[9];

if (($Serial_PI_read eq $Serial_PI) || ($Serial_MSC_read eq $Serial_MSC))
{
	printf "Serial mismatch!\n";
	printf "MSC board ID: is $Serial_MSC_read - should be $Serial_MSC\n";
	printf "PI board ID:  is $Serial_PI_read - should be $Serial_PI\n";
	printf "\n";
	exit 1;
}

printf "Serials written and checked.\n";
