#!/usr/bin/perl -w

=head1 NAME

isos-ver - Utility to display version information for an ATMOS source tree

=head1 SYNOPSIS

B<isos-ver> [-h | -f <version file> | -d <version directory>]

=head1 DESCRIPTION

isos-ver is a script which displays the content of ISOS Version Information files.
It can parse a specific file, parse all ISOS Verison Information files in a specific
directory; or, when invoked with no arguments, trys each directory from a default list
in turn until it finds one which exists.

=head1 OPTIONS

=over 4

=item -h

Display help and usage.

=item -f <version file>

Parse the specified ISOS Version Information file.

=item -d <version directory>

Look in the specified directory for ISOS Version Information files.
If none is specified, isos-ver will try B<version_info> and
b<atmos/version_info>

=cut

use strict;

use File::Basename;

# History
# 1.0: Initial version, support version "1.0" of .ivi files
#


# Configuration data
my $script_version = "ISOS version information v1.0";
my $file_ext = "ivi";
my @default_ver_dirs = ("version_info", "atmos/version_info");
# End of configuration data

my $scriptname = basename($0);

# Parse command line options
my $o;
my $filename = undef;
my $ver_dir = undef;

while (defined($o = shift(@ARGV)))
{
    if ($o eq "-h")
    { &display_help }
    elsif ($o eq "-f") # A filename has been specified
    { $filename = shift(@ARGV) }
    elsif ($o eq "-d") # A directory has been specified - this should override the default
    { $ver_dir = shift (@ARGV) }
    else
    { die "$scriptname: Unrecognised option $o\n" }
}

if (defined($filename))
{
    # These was a filename specified on the command line
    print &parse_file($filename);
}
else
{
    # No specific filename - parse all files in the directory
    # If a directory was specified - use that
    unless (defined($ver_dir))
    {
        # Otherwise try one from the list
        foreach my $i (@default_ver_dirs)
        {
            if (-d $i)
            {
                $ver_dir = $i;
                last;
            }
        }
        unless (defined($ver_dir))
        { die "$scriptname: Could not find a valid directory (tried: @default_ver_dirs)\n" }
    }

    # Find all files in the directory with the correct extension, and parse them
    my ($f, $major_ver, $report_tmp, $report) = (undef, undef, undef, "");
    my @major_vers = ();
    opendir(DIR, $ver_dir) or die "$scriptname: Could not open directory $ver_dir: $!\n";
    while (defined ($f = readdir(DIR)))
    {
        next unless ($f =~ /\.$file_ext$/); # Skip this unless it matches the correct extension
        ($major_ver, $report_tmp) = &parse_file($ver_dir . "/" . $f); # Parse the file
        $report .= $report_tmp;
        push(@major_vers, $major_ver) if defined($major_ver); # Record the major software version
    }
    closedir (DIR);

    # Generate a list of unique major versions that were found.
    # Do this by generating a hash, using the major software version as the key
    my %major_vers;
    foreach my $i (@major_vers)
    { $major_vers{$i} = 1 }

    # Check if there is more than one major software version
    if ((keys %major_vers) > 1)
    { print "\nWARNING: There are conflicting major software versions!\n" }

    # Check that some files were actually parsed
    if ($report ne "")
    { print "Version directory: $ver_dir\n\n" . $report . "\n" }
    else
    {
        # No version files were found.
        print "$scriptname: No version files were found in directory $ver_dir\n";
    }

    # Look to see if we seem to have tools installed, and run the 'virata-tools-ver' command if so
    unless (defined($ENV{'ATMOSTOOLS'}))
    { print "No Virata tools can be found.\n"; }
    else
    {
        system("virata-tools-ver");
    }
}

exit 0;

sub parse_file
{
    my $filename = shift;
    die "$scriptname: No filename defined in parse_file" unless defined($filename);

    my %v;
    $v{UNKNOWN} = ""; # Field for lines which don't match known format

    open(FH, $filename) or die "$scriptname: Could not open $filename for reading: $!\n";
    while (<FH>)
    {
        chomp;
        next if (/^\s*$/); # Skip blank lines or whitespace lines
        if (/^([^\:]+)\s*\:\s*(.*)$/) # Match "foo : bar";
        { $v{lc($1)} = $2 } # Lower-case keys, and put it into the hash
        else
        { $v{UNKNOWN} .= $_ . "\n" } # Couldn't parse it - put it into the unkown key
    }
    close (FH);
    
    die "$scriptname: No version number in file $filename\n" unless defined($v{'isos-version-format'});
    my $result = "";
    my $major_ver = undef;

    # Determine which format the version file is in.
    if ($v{'isos-version-format'} eq "1.0")
    {
        # This is version 1.0
        # Check if all the fields we need are defined
        unless (&chk_def(\%v, ['document', 'document-issue', 'description', 'isos-major-ver']))
        { $result = basename($filename) . " appears to be corrupt/incomplete\n" }
        else
        {
            # Format as "<document> <issue>: (<major-ver>) <description>
            $result = $v{'document'} . " (issue " . $v{'document-issue'} . ") : (" . $v{'isos-major-ver'} . ") " . $v{'description'} . "\n";
            $major_ver = $v{'isos-major-ver'};
        }
    }
    else
    {
        # We do not recognise the version string
        $result = basename($filename) . ": in unsupported version " . $v{'isos-version-format'} . "\n";
    }

    # If we were called in list context, return a list of major version and the text string.
    # Otherwise, just return the text string
    if (wantarray)
    { return ($major_ver, $result) }
    else
    { return $result }
}

sub chk_def
{
    # Take a reference to a hash, and a reference to a list of keys.
    # Check that every one of the list of keys exists in the hash
    # Return 0 if at least one key doesn't exist, otherwise return 1
    my ($v_ref, $p_ref) = @_;
    foreach my $p (@{$p_ref})
    { return 0 unless defined($v_ref->{$p}) }

    return 1;
}

sub display_help
{
    print <<EOT;
$script_version
Usage: $scriptname [-f <version file>] [-d <version directory>]

This script displays version information about an ISOS tree.

EOT
    exit 0;
}
