#!/usr/bin/perl -w
# Get necessary packages from remote url.
# Find out the necessary package list from the prjconf
# Code by Leaf( lifu.zhang@elektrobit.com )

use strict;
use MIRemote;

#Add slash for these 2 value:
my $remote_repo = 'http://repo.meego.com/MeeGo/releases/1.0/core/repos/ia32/packages/'; #needs slash
my $storage = '/obs/build/'; #needs slash
my $help = 'USAGE: obsmi prj repo [--verbose]'."\n";

my ($prj, $repo, $arch ) = @ARGV;
if( !defined( $prj ) || !defined($repo) || !defined($arch) ){
	print $help;
	exit(0);	
}
my $verbose = 0;
#analyze the arguments
foreach my $opt (@ARGV){
	if( $opt =~ /^-(.+)/ ){
		my $curopt = $1;
		if( $curopt =~ /(^v$|-verbose)/ ){#accept both short & long option
			$verbose = 1;
		}
	}
}

my $prjconf = `oscl meta prjconf $prj`; #fetch prjconf
die "Unable to fetch prjconf" if( $? != 0 );
#TBD: check prjconf after fetch;

my @cnflines = split( "\n", $prjconf );

my @pkgs;
my @hostpkgs;
foreach my $line (@cnflines){
	chomp $line;
	if( $line =~ /^(Support|VMinstall)\s*:\s*(.+\S)/g ){
		print "Found host package: $2\n" if( $verbose );
		push @hostpkgs, split(/\s+/, $2);
	} elsif( $line =~ /^(Preinstall|Required|Keep|Prefer)\s*:\s*(.+\S)/g ){
		foreach my $nm ( split( /\s+/, $2 ) ){
			print "Found target pkg $nm\n" if( $verbose );
			push @pkgs, $nm if( $nm !~ /^-/ ); 
		}
	} elsif( $line =~ /Substitude\s*:\s*(\S+)\s+(\S+)/g ){
		print "Found substitude: $1,$2\n" if ($verbose);
		push @pkgs, $2 if( defined ($2) );
	}
}

if( $verbose ){
	print "-------------------------\nPackages for host:\n".join( "\n", @hostpkgs )."\n";
	print "-------------------------\nPackages for target:\n".join( "\n", @pkgs )."\n";
}

print "FETCH LIST: $remote_repo.$arch";
my %hreflist = MIRemote::fetchlist( $remote_repo.$arch );
my $downtar = $storage.$prj.'/'.$arch.'/:full/';
print "KEYS: ", keys(%hreflist), " \n";
foreach my $pknm (@pkgs, @hostpkgs){
	if( exists $hreflist{$pknm} ){
		my $href = $hreflist{$pknm};
		MIRemote::fetchpkg( $href, $downtar, $verbose );
	} else {
		print STDERR "'$pknm' Not found\n";
	}
}

