#!/usr/bin/perl -w

use strict;

use File::Basename;

my $scriptname = basename($0);

my $metamk_version = "metamk v1.4";

my $config_file = undef; # The configuration file for this build
my $metamk_cfg_file = "config/products/include/metamk.cfg"; # The default location of the metamk config file
my $verbose = 0; # Default to not being verbose
my ($build_config_start, $build_config_end) = ("START BUILD CONFIG", "END BUILD CONFIG"); # Labels around build config
my $req_mkproduct_ver = 1.10; # The required version of mkproduct

my %info_src = (); # Info name to information source
my %info_val = (); # Info name to value
my %cmd = (); # Mapping from command name to command string to parse and run
my %sources = (); # Hash just listing all the required sources
my %flashfs = (); # Hash from flashfs name to pointer to array of filename pairs
my %flashfs_ok = (); # Hash from flashfs name to flag indication whether we should use this partition or not
my %flashfs_size = (); # Hash from flashfs name to flashfs size
my %flashfs_offset = (); # Hash from flashfs name to flashfs offset
my %flashfs_cfgfile = (); # Hash from flashfs name to flashfs config file
my %flashfs_binfile = (); # Hash from flashfs name to flashfs binary file
my %flashfs_flags = (); # Hash from flashfs name to list of flags
my $fsorder = undef; # Space separated list of flashfs names which specifies their order

# Verify that we've been called from mkproduct, and check MKPRODUCT_VERSION

my $mkproduct_ver = $ENV{'MKPRODUCT_VERSION'};
unless (defined($mkproduct_ver))
{ die "$metamk_version\n$scriptname is only intended to be run from within mkproduct - it should not be run directly\n" }

unless ($mkproduct_ver >= $req_mkproduct_ver)
{ die "$scriptname: Version $req_mkproduct_ver or later of mkproduct is required\n" }

&process_args;

#
# Determine the location of the metamk configuration file
#

# This can be overridden by the shell variable 'METAMK_CONFIG_FILE' (set by the mkproduct world)

$metamk_cfg_file = $ENV{'METAMK_CONFIG_FILE'} if (defined($ENV{'METAMK_CONFIG_FILE'}));
print "metamk config file: $metamk_cfg_file\n" if ($verbose);

#
# Determine if we're network booting - look at the NETWORK_BOOT environment variable
#

my $network_boot = $ENV{'NETWORK_BOOT'} || 0; # Default to 0 if it isn't set.
print "Network booting selected\n" if ($network_boot && $verbose);

#
# Discover our product build directory
#

my $product_build_dir = $ENV{'PRODUCT_BUILD_DIR'};
die "PRODUCT_BUILD_DIR not defined - this should never happen as it is set by mkproduct\n" unless defined($product_build_dir);

#
# Read in and process the metamk configuration file
#

&process_metamk_cfg($metamk_cfg_file);

#
# Now go round and process the required sources
#
foreach my $s (keys %sources)
{ &process_source_cfg($s) }

# Determine if we have any flashfs partitions we should discard if we're network booting
# ie, they have the 'skipnet' flag

if ($network_boot)
{
    foreach my $fs (keys %flashfs)
    {
        next unless ($flashfs_ok{$fs});
        if (defined($flashfs_flags{$fs}) && ($flashfs_flags{$fs} =~ /\bskipnet\b/)) # The flags containt 'skipnet'
        {
            print "flashfs '$fs' has the 'skipnet' flag set - discarding\n" if ($verbose);
            $flashfs_ok{$fs} = 0; # Mark this partition as not to be used
        }
    }
}


&display_summary_info if ($verbose);

#
# Generate mkflashfs configuration
#

# Check that the order is specified, but if there is only one partition, and fsorder is not specified, use that as the fsorder
unless (defined ($fsorder))
{
    if (scalar(keys %flashfs) == 1)
    {
        my @keys = keys %flashfs;
        $fsorder = $keys[0];
    }
    else
    { die "$scriptname: keyword 'fsorder' must be specified - there is more than one flashfs partition\n" }
}

foreach my $fs (keys %flashfs)
{
    # Skip this one if the OK flag is not set.
    next unless ($flashfs_ok{$fs});

    my $cfgfile = $flashfs_cfgfile{$fs} = "$product_build_dir/flashfs_$fs.cfg";
    $flashfs_binfile{$fs} = "$product_build_dir/flashfs_$fs.bin";
    my $cfg = "";
    foreach my $f (@{$flashfs{$fs}})
    { $cfg .= "file " . &expand_string($f->[0]) . " " . &expand_string($f->[1]) . "\n" }
    open (FH, ">" . $cfgfile) or die "Could not open $cfgfile for writing: $!";
    print FH $cfg;
    close FH;

    # Check that this partition appears in the fsorder list
    unless ($fsorder =~ /\b$fs\b/)
    { die "$scriptname: flashfs '$fs' is not specified in the fsorder list\n" }
}

# Now sort the flashfs definitions in order of offset
my $flashfs_defs;
foreach my $fs (split(/\s+/, $fsorder))
{
    next unless ($flashfs_ok{$fs}); # Skip this partition unless the OK flag is set.
    my $off = 0;
    # Only specify the offset of this partition if it was specified to us, and it is
    # NOT a network boot build.
    if (defined($flashfs_offset{$fs}) && ($flashfs_offset{$fs} != 0) && !$network_boot)
    { $off = $flashfs_offset{$fs} } 
    $flashfs_defs .= " " . $flashfs_binfile{$fs} . " " . $off;
}

&set_info("flashfs_defs", "<INTERNAL>", $flashfs_defs);

#
# Run commands
#

&execute("boot");
&execute("configinfo");
foreach my $fs (keys %flashfs)
{
    next unless ($flashfs_ok{$fs});
    # Set up parameters for this flashfs    
    my $ffs_size = $flashfs_size{$fs} || 0; # Default to 0 if it hasn't been defined
    $ffs_size = 0 if ($network_boot);
    &set_info("flashfs_size", "<INTERNAL>", $ffs_size);
    &set_info("flashfsfile", "<INTERNAL>", $flashfs_binfile{$fs});
    &set_info("flashfscfg", "<INTERNAL>", $flashfs_cfgfile{$fs});
    &execute("flashfs");
}

if ($network_boot)
{ &execute("joinnet") }
else
{ &execute("joinflash") }

exit 0;

sub process_args
{
    # Iterate through arguments
    while (defined($ARGV[0]))
    {
        $_ = shift (@ARGV);
        if (/^\-v$/) # -v => verbose
        { $verbose = 1 }
        elsif (/^[^\-]/) 
        {
            # Doesn't start with a '-' - check to see if it's the remaining argument, and use it as config file
            &usage if (defined($ARGV[0])); # Die if this isn't the last argument
            $config_file = $_;
        }
        else # We don't understand this argument
        { &usage }
    }

    # Now verify that we've got something sensible
    &usage unless (defined($config_file));

    # The main config file maps onto a special information element - MAIN_CFG_FILE
    &set_info('MAIN_CFG_FILE', "<INTERNAL>", $config_file);
}

sub process_metamk_cfg
{
    my $fname = shift;
    open (FH, $fname) or die "$scriptname: Could not open file '$fname' for reading: $!\n";
    while (<FH>)
    {
        chomp;
        s/\r//g; # Strip off carriage returns, needed for windows line-endings
        s/^\s*([^\s]*)\s*$/$1/; # Strip off leading and trailing whitespace
        next if (/^\s*\%/ || /^\s*$/); # Skip if it is a blank line, or a line containing only comments
        if (/^IMPORT\s+(\w+)$/) # IMPORT <variable>
        { &import_var($1) }
        elsif (/^INFO\s+(\w+)\s+(\S+)(?:\s+DEFAULT\s+(.*))?$/) # INFO <variable> <source> [DEFAULT <default>]
        {
            my $varname = $1;
            my $varsrc = $2;
            my $var_default = $3; # Note this may be undefined - this is intentional
            $varsrc = &expand_string($varsrc);
            &set_info($varname, $varsrc, $var_default);
        }
        elsif (/^CMD\s+(\w+)\s+(.*)$/) # CMD <name> <command string>
        {
            $cmd{$1} = $2; # Note: do NOT expand string now
        }
        else
        { die "$scriptname: Unrecognised line >$_< in metamk configuration file $fname\n" }
    }
    close FH;
}

sub process_source_cfg
{
    my $fname = shift;
    my $old_slash = $/;
    undef $/; # Suck whole files at once, rather than line at a time
    open (FH, $fname) or die "$scriptname: Could not open file '$fname' for reading: $!\n";
    my $src = <FH>;
    close FH;
    $/ = $old_slash; # Reset to original value
    
    # Look for the start of the build configuration
    return unless ($src =~ /^\s*(\S*)\s*$build_config_start\s*$/m);
    
    my $comment_char = $1; # This appears to be the comment character in this particular file
    # Extract just the config block    
    unless ($src =~ /$comment_char\s*$build_config_start\s*\n(.*)\n\s*$comment_char\s*$build_config_end/s)
    {
        print STDERR "Config info found (comment char - $comment_char), but could not be extracted";
        return;
    }

    # Now step through config block
    my $curr_flashfs = "";
    foreach (split('\n', $1))
    {
        s/\r//g; # Strip off carriage returns, needed for windows line-endings
        next unless (s/^\s*$comment_char\s*(.*?)\s*$/$1/); # Strip comment character from front
        next if (/\#/) ; # Skip this line if it now starts with a metamk comment '#'
        next if (/^$/); # Skip empty line

        if ($curr_flashfs)
        {
            # We're inside a flashfs definition
            if (/^file\s*(\S+)\s+(\S+)$/) # match "file foo bar"
            { &add_file_to_flashfs($curr_flashfs, $1, $2) }
            elsif (/dir\s*(\S+)$/) # match "dir foo"
            { &add_dir_to_flashfs($curr_flashfs, &expand_string($1)) }
            elsif (/size\s*(.+)$/) # match "size <num>"
            { $flashfs_size{$curr_flashfs} = $1 }
            elsif (/offset\s*(.+)$/) # match "offset <num>"
            { 
                my $offset = $1;
                if ($offset =~ /^(\d+)k$/) # Offset is in bytes - check for a 'k' suffix
                { $offset = $1 * 1024 }
                $flashfs_offset{$curr_flashfs} = $offset;
            }
            elsif (/flags\s*(.+)$/) # match "flags <flags>"
            {
                if (defined($flashfs_flags{$curr_flashfs}))
                { $flashfs_flags{$curr_flashfs} .= " " . $1}
                else
                { $flashfs_flags{$curr_flashfs} = $1 }
            }
            elsif (/^end$/)
            { $curr_flashfs = "" }
            else 
            { die "$scriptname: Unrecognised string $_ in flashfs $curr_flashfs section of $fname\n" }
        }
        else
        {
            # We're NOT inside a flashfs definition
            if (/^flashfs\s*(\S+)$/) # Keyword was flashfs
            {
                $curr_flashfs = $1;
                unless (defined($flashfs{$curr_flashfs})) # If this is the first reference to this partition, define it
                {
                    $flashfs{$curr_flashfs} = [];
                    $flashfs_ok{$curr_flashfs} = 1;
                }
            }
            elsif (/^fsorder\s*(.+)$/) # Keyword was fsorder
            {
                die "$scriptname: fsorder redefined in file $fname\n" if (defined($fsorder));
                $fsorder = $1;
            }
            elsif (/^include\s*(.+)$/) # Keyword was include
            {
                # We should include the named file
                my $fname = $1;
                # Check the file exists
                die "$scriptname: include file '$fname' does not exist, or is not readable\n" unless (-r $fname);
                # Process configuration from the file
                &process_source_cfg($fname);
            }
            elsif (/^(\w+)\s+(.*)$/) # Match "<keyword> <stuff>"
            { 
                my $keyword = $1;
                my $val = $2;
                # Check to see if this is an information element
                if (exists($info_src{$keyword}))
                { $info_val{$keyword} = $val } # Found keyword that we want - set it
                else
                { die "Unrecognised line >$_< in $fname (keyword '$keyword' not found)\n" }
            }
            else
            { die "Unrecognised line >$_< in $fname\n" }
        }        

    }
}


        
sub usage
{
    print "Usage: \n$scriptname -v <config file>\n";
    exit 1;
}

sub set_info
{
    my ($vn, $vs, $val) = @_;
    $info_src{$vn} = $vs;
    $info_val{$vn} = $val if defined($val);
    unless ($vs =~ /^\<.*\>$/) # Unless in special format <foo>
    {
        if (defined($sources{$vs})) # If this source is already required
        { push (@{$sources{$vs}}, $vn) } # Add this name to the list for this source
        else # If this is the first thing to require this source
        { $sources{$vs} = [$vn] }
    }
}

sub import_var
{
    my $var = shift;
    my $v = $ENV{$var};
    return unless (defined($v));

    &set_info($var, "<IMPORTED>", $v);
}

sub expand_string
{
    my $str = shift;
    my $recurse_chk = shift || 5;

    die "$scriptname: Internal error - recursion too deep in expand_string" if ($recurse_chk <1);

    my @refs = $str =~ /\$\{(\w+)\}/g;

    # If there are no variable references, return unmangled string
    return $str if ($#refs == -1);

    foreach my $r (@refs)
    {
        unless (defined($info_val{$r}))
        {
            # The value doesn't exist - check if the information element exists
            if (defined($info_src{$r}))
            { die "$scriptname: Reference to $r which should be found in $info_src{$r}, but has no value, and no default\n" }
            else # No IE - check if there is an appropriately named shell variable
            {
                if (defined($ENV{$r}))
                {  &import_var($r) }
                else
                { die "$scriptname: Reference to variable $r in >$str<, which is undefined\n" }
            }
        }

        # Now patch the value
        unless ($str =~ s/\$\{$r\}/$info_val{$r}/)
        { die "Could not patch \${$r} in >$str<\n" }
    }
    return expand_string($str, $recurse_chk);
}

sub dump_all_data
{
    print "\n$scriptname: dumping all data\n\n";

    print "Information elements\n";
    print "====================\n\n";
    foreach my $k (keys %info_src)
    { print "$k: $info_src{$k} = " . (defined($info_val{$k}) ? $info_val{$k} : "<undefined>") . "\n" }
    print "\n";

    print "Information sources\n";
    print "===================\n\n";
    foreach my $i (keys %sources)
    { print "$i: " . join(" ", @{$sources{$i}}) . "\n" }
    print "\n";
#    print join("\n", keys (%sources)) . "\n\n";

    print "Commands\n";
    print "========\n\n";
    foreach my $k (keys %cmd)
    { print "$k => $cmd{$k}\n" }
    print "\n";

    print "Flash FS's\n";
    print "==========\n\n";
    foreach my $fs (keys %flashfs)
    {
        print "Flashfs: $fs\nflashfs_ok=$flashfs_ok{$fs}\n";
        if (defined($flashfs_size{$fs}))
        { print "Size $flashfs_size{$fs}\n" }
        else
        { print "Auto-sizing\n" }
        if (defined($flashfs_flags{$fs}))
        { print "Flags: $flashfs_flags{$fs}\n" }
        foreach my $f (@{$flashfs{$fs}})
        { print &expand_string($f->[0]) . " $f->[1]\n" }
    }
    
}

sub display_summary_info
{
    foreach my $fs (keys %flashfs)
    {
        next unless ($flashfs_ok{$fs});
        print "\nFlashfs $fs:\n\n";
        print defined($flashfs_size{$fs}) ? "Size $flashfs_size{$fs} " : "Auto-sizing ";
        print defined($flashfs_offset{$fs}) ? "offset $flashfs_offset{$fs}\n" : "no offset set\n";
        if (defined($flashfs_flags{$fs}))
        { print "Flags: $flashfs_flags{$fs}\n" }

        foreach  my $f (@{$flashfs{$fs}})
        { print &expand_string($f->[0]) . " $f->[1]\n" }
        print "\n";
    }
}

sub add_file_to_flashfs
{
    my ($fs, $src, $dest) = @_;
    unless (defined($flashfs{$fs}))
    { $flashfs{$fs} = [[$src, $dest]] }
    else
    {
        # Check if a file of this name already exists
        my $found = 0;
        foreach my $i (@{$flashfs{$fs}})
        {
            if ($i->[1] eq $dest)
            {
                print "File $src overrides previously added $i->[0] in flashfs $fs\n" if ($verbose);
                $i->[0] = $src;
                $found = 1;
                last;
            }
        }
        push(@{$flashfs{$fs}}, [$src, $dest]) unless ($found);
    }
}

            
sub add_dir_to_flashfs
{
    my ($fs, $dirname) = @_;
    # Fail silently if it doesn't exist - TBD - REVIEW!
    return unless (-d $dirname);
    $dirname .= "/" unless ($dirname =~ /\/$/); # Ensure there's a trailing /
    
    opendir(DIR, $dirname) or die "Could not open directory $dirname for reading: $!";
    my $fname;
    while (defined($fname = readdir(DIR)))
    {
        next if ($fname =~ /^\./); # Skip files starting with .
        my $srcname = $dirname . $fname;
        next unless (-f $srcname); # Only include files
        &add_file_to_flashfs($fs, $srcname, $fname);
    }
    closedir(DIR);
}

sub execute
{
    my $c = shift;
    unless (defined($cmd{$c}))
    { die "Command $c is not defined in the configuration file\n" }

    my $str = &expand_string($cmd{$c});
    print "\n$str\n" if ($verbose);
    my $ret = system($str);
    if ($ret)
    { die " Error from $str\n" }
}

