#!/usr/bin/perl
my @file=`rpm -ql $ARGV[0]`;
my $rpminfo=`rpm -qi $ARGV[0]`;
my @rpminfo=split /\n/,$rpminfo;
my %info;
my $i=0;
my $desc_ind;
foreach my $head (@rpminfo[0..10]){
$head=~s/Relocation.*//g;
$head=~s/Vendor:.*//g;
$head=~s/Build Date.*//g;
$head=~s/Install Date:.*//g;
$head=~s/Signature.*//g;
$head=~s/Source RPM.*//g;
$head=~s/Size.*?L/L/g;
#print $head,"\n";
$i++;
$desc_ind=$i if substr($head,0,4) eq Desc;
@info=split /:/,$head,2;
$info[0]=~s/\s+//g;
$info{$info[0]}="$info[1]";
}
my @desc;
my $end =(scalar @rpminfo)-1;
print $desc_ind,"\n";
foreach my $description (@rpminfo[$desc_ind..$end]){
push (@desc,$description);
push (@desc,"\n");
}

$info{'%description'}=join('',@desc);

my $src_pre='/usr/src/redhat/SOURCES/';
$name="$info{'Name'}-$info{'Version'}-$info{'Release'}";
$name=~s/ //g;
#$files=~s/\n//g;
my $files=join(' ',@file);
$files=~s/\n//g;
my $dir_tar= "$info{'Name'}-$info{'Version'}";
$dir_tar=~s/ //g;
mkdir $dir_tar;
print $dir_tar;
`cp -rp $files $dir_tar`;
`tar cjvf $src_pre$name\.tar\.bz2 $dir_tar`;
`rm -rf $dir_tar`;

unlink 'testr.spec';
open (SPEC,">>",'testr.spec') ;
print SPEC 'Summary      :   ',$info{'Summary'},"\n";
print SPEC 'Name         :   ',$info{'Name'},"\n";
print SPEC 'Version      :   ',$info{'Version'},"\n";
print SPEC 'Release      :   ',$info{'Release'},"\n";
print SPEC 'License      :   ',$info{'License'},"\n";
print SPEC 'Group        :   ',$info{'Group'},"\n";
print SPEC 'URL          :   ',$info{'URL'},"\n";
#rint SPEC 'License      :   ',$info{'License'},"\n";
print SPEC 'Source       :   '," $src_pre$name\.tar\.bz2","\n\n";
print SPEC '%description',"\n"; 
print SPEC $info{'%description'},"\n";
#print SPEC $info{'Name'};
#print SPEC $info{'Name'};


print SPEC '%prep',"\n";
print SPEC '%setup',"\n";

print SPEC '%clean',"\n";

print SPEC '%post',"\n";
print SPEC '%files',"\n";
print SPEC '%defattr(-, root, root, 0755)',"\n\n";

print SPEC @file;

close SPEC;

`rpmbuild -bb testr.spec`;
