#!/usr/bin/perl -W

# Copyright (C) 2000,2001 Mandrakesoft
# Author David Odin <odin@mandrakesoft.com>
# 
# $Id: download_packages.pl,v 1.9 2001/06/05 16:21:32 philippe Exp $
#

# version 0.2
# The purpose of this script is to download the packages given
# on the command line or in the $PackagesList variable.

# First get the transaction name (FIRST STEP IN ALL SCRIPTS)
my $transaction_name = shift @ARGV if @ARGV;

my $mandrake_release = "snf7.2";
my $download_rep = "/var/cache/";

# if $test = 1, the package list is taken on the command-line
# if $test = 0, the package list is taken from the proxy variable config file
my $test = 0;

# First part, get the config variables...
my ($CurrentMirror, $PackagesList);

if ($test)
{
  $CurrentMirror = $ARGV[0];
  $PackagesList = $ARGV[1];
} else
{
  if (! $transaction_name ) {
	$transaction_name = "$$";
	# initialize a backend transaction
	system ("config-wrapper.pl $transaction_name -i");
  }

  # Get the CurrentMirror value
  $CurrentMirror = `config-wrapper.pl $transaction_name -g CurrentMirror`;
  chomp $CurrentMirror;
  # Get the PackagesList
  $PackagesList = `config-wrapper.pl $transaction_name -g PackagesList`;

  if ( $transaction_name eq "$$" ) {
      # cleanup the transaction
      system ("config-wrapper.pl $transaction_name -a");
  }
}


my ($arch, $rep, @list);

$rep="";

# now get the list of updatable packages
open F, "curl -s $CurrentMirror/$mandrake_release/ls-lR |";
foreach (<F>)
{
  if (/^([^ ]+):$/)
  {
    $rep = "updates/$mandrake_release/$1";
  } elsif (/^(-|l)/)
  {
    $rep =~ /SRPMS/ and next;
    my @l = split;
    push @to_update, "$l[8]" if $l[8];
  }
}
close F or die;

# Find the architecture and set $rep accordingly

$arch = `uname -m | sed -e s/i.86/i586/ -e s/sun4u/sparc64/ -e s/arm.*/arm/ -e s/sa110/arm/`;
chop $arch;

if ($arch =~ /i586/)
{
  $rep = "/RPMS";
} else
{
  $rep = "/$arch/RPMS";
}

# now do the download
$PackagesList =~ s/,/|/g;
chomp $PackagesList; # beware of '\n' at the end of the last name

print STDERR "Packages to download: $PackagesList \n";

foreach (@to_update)
{
  m!(^|/)($PackagesList)-([^-]+)-([^-]+)\.[^.]+\.rpm$! or next;

  print STDERR "Downloading package $_ in directory $rep on $CurrentMirror/$mandrake_release$rep \n";

  `curl -s "$CurrentMirror/$mandrake_release$rep/$_" -o "$download_rep$_";`

}

 
