#! /usr/bin/perl -w
#
# Rsync RPM Update Version 1.0, MinLinux(Mandrake) Distribution tools 0.1.
# Copyright: GPL 2.0 and up.
# Created by Troels Liebe Bentsen <tlb@iname.com>
#
# Perl Program: 2
#
# ChangeLog:
#
# 2000-09-20	First Release 1.0
#
# TODO:
# Check for bad and duplicate rpm names.
# Make it do all the RPMS i one look up.

use strict;

# This my be changed:
my $localmirror   = '/dist/Mandrake';
my $remotemirror  = 'rsync://sunsite.uio.no:873:/Mandrake-devel/';

$localmirror  =~ s|/$||;
$remotemirror =~ s|/$||;

# Cooker
print "$localmirror".'/cooker/Mandrake/RPMS/'."\n";
renamefiles("$remotemirror".'/cooker/Mandrake/RPMS/', "$localmirror".'/cooker/Mandrake/RPMS/');

# SRPMS
print "$localmirror".'/SRPMS/'."\n";
renamefiles("$remotemirror".'/SRPMS/', "$localmirror".'/SRPMS/');

# 7.2 beta
print "$localmirror".'/7.2beta/i586/Mandrake/RPMS/'."\n";
renamefiles("$remotemirror".'/7.2beta/i586/Mandrake/RPMS/', "$localmirror".'/7.2beta/i586/Mandrake/RPMS/');

# 7.2 beta SRPMS
print "$localmirror".'/7.2beta/SRPMS/'."\n";
renamefiles("$remotemirror".'/7.2beta/SRPMS/', "$localmirror".'/7.2beta/SRPMS/');

# Contrib
print "$localmirror".'/contrib/RPMS/'."\n";
renamefiles("$remotemirror".'/contrib/RPMS/', "$localmirror".'/contrib/RPMS/');

# Contrib SRPMS
print "$localmirror".'/contrib/SRPMS/'."\n";
renamefiles("$remotemirror".'/contrib/SRPMS/', "$localmirror".'/contrib/SRPMS/');

print "\n";
# The RSync stuff.
my @args = ('rsync -av -H -S -b --partial --delete --progress --stats '.$remotemirror.'/ '.$localmirror.'/');
system(@args) == 0 or die "system @args failed: $?";

sub renamefiles {
 my $rsyncmirror = shift;
 my $localmirror = shift;
 # Make the localhash list.
 my %locallist;
 $localmirror =~ s|/$||; # remove a slash in the end if it is there
 if (-d $localmirror) {
   opendir DIR, "$localmirror" or die "opendir: $!\n";  
   foreach my $file (grep { ! -d } readdir DIR) {
     if ($file =~ /([^\/]*)(-[^-\/]*){2}mdk.*rpm$/) {
       $locallist{$1} = $file;
     }
   } 
   closedir DIR; 
 }
 else { 
   die "opendir: $!\n" 
 };

 # Get Rsync filelist.
 my @rsyncrpmslist;
 open (LIST, "rsync -anv $rsyncmirror |");
 @rsyncrpmslist = map { split "\n" } <LIST>;   
 close (LIST);
 
 # Rename the files 
 foreach my $file (@rsyncrpmslist) {
  $file =~ s/^.*\s//; # Remove crap from rsync output
  $file =~ s/^.*\///; # Remove all until / 
  if ($file =~ /([^\/]*)(-[^-\/]*){2}mdk.*rpm$/) {
   if (($locallist{$1}) and ($locallist{$1} ne $file)) {
    print "Move $locallist{$1} to $file\n";
    rename($localmirror.'/'.$locallist{$1} , $localmirror.'/'.$file) || 
    die "Can't rename $localmirror.'/'.$locallist{$1} to $localmirror.'/'.$file: $!";
   }
  }
 } 
}
