#!/usr/bin/perl -w

use strict;
use ProjectBuilder::Base;
use ProjectBuilder::Distribution;
use File::Copy;

# This script help transforming a pre-0.9.11 repository into the new format 
# where the arch subdirectory is now required to host the packages
# for rpm based packages

# Needs to be launch at the root of the ftp server
# Script is idempotent: can be relaunched on itself

for my $odir (<*>) {
	next if (! -d $odir);
	chdir($odir);
	for my $over (<*>) {
		next if (! -d $over);
		my ($ddir, $dver, $dfam, $dtype, $dos, $pbsuf, $pbupd, $pbins, $arch) = pb_distro_init($odir,$over);
		# Repo only change for rpm packages in 0.9.11
		next if ($dtype ne "rpm");
		chdir($over);
		pb_mkdir_p("i386");
		pb_mkdir_p("x86_64");
		for my $p (<*>) {
			system("rm -rf $p") if (($p eq "headers") || ($p eq "media_info") || ($p eq "repodata"));
			unlink($p) if (($p eq "hdlist.cz") || ($p eq "synthesis.hdlist.cz"));
			next if (($p eq "i386") || ($p eq "x86_64"));
			if ($p =~ /\.i[3456]86\.rpm$/) {
				print("Move $p to i386\n");
				move("$p","i386");
			}
			if ($p =~ /\.x86_64\.rpm$/) {
				print("Move $p to x86_64\n");
				move("$p","x86_64");
			}
			if ($p =~ /\.ia64\.rpm$/) {
				print("Move $p to ia64\n");
				pb_mkdir_p("ia64");
				move("$p","ia64");
			}
			if (($p =~ /\.src\.rpm$/) || ($p =~ /\.noarch\.rpm$/) || ($p =~ /\.spec$/)) {
				print("move $p to i386 and x86_64\n");
				copy("$p","x86_64");
				move("$p","i386");
			}
			if ($p =~ /\.repo$/) {
				open(SRC,$p);
				open(I386, "> i386/$p");
				open(X86_64, "> x86_64/$p");
				while (<SRC>) {
					if (/^baseurl=/) {
						my $ti = $_;
						my $tx = $_;
						$ti =~s/$over$/$over\/i386/;
						print I386 "$ti";	
						$tx =~s/$over$/$over\/x86_64/;
						print X86_64 "$tx";	
					} else {
						print I386 "$_";
						print X86_64 "$_";	
					}
				}
				close(I386);
				close(X86_64);
				close(SRC);
				print("adapt $p into i386 and x86_64\n");
				unlink($p);
			}
			if ($p =~ /\.addmedia$/) {
				open(SRC,$p);
				open(I386, "> i386/$p");
				open(X86_64, "> x86_64/$p");
				while (<SRC>) {
					my $ti = $_;
					my $tx = $_;
					$ti =~s/$over with/$over\/i386 with/;
					print I386 "$ti";	
					$tx =~s/$over with/$over\/x86_64 with/;
					print X86_64 "$tx";	
				}
				close(I386);
				close(X86_64);
				close(SRC);
				print("adapt $p into i386 and x86_64\n");
				unlink($p);
			}
		}
		system("cd i386 ; yum-arch . ; createrepo .");
		system("cd ia64 ; yum-arch . ; createrepo .") if (-d "ia64");
		system("cd x86_64 ; yum-arch . ; createrepo .");
		system("cd i386 ; genhdlist2 --clean .") if ($dfam eq "md");
		system("cd x86_64 ; genhdlist2 --clean .") if ($dfam eq "md");
		chdir("..");
	}
	chdir("..");
}
