#!/usr/bin/perl

use Tie::File;
use strict;

sub banner {
	print <<"END";
Use: $0 [opts]
Opts:
-l [local] cria lista para manipular os SlackBuild's que deverão ser compilados(DEVE SER EXECUTADO EM PRIMEIRO LUGAR)

-s [gcc flags] muda os flags do gcc(SENÃO FOREM FORNECIDOS ARGUMENTOS, SERÁ COMPILADO NO PADRÃO DO SLACKBUILD). Ex: $0 -s "-O3 -march=i686 -mcpu=i686"

-c processa todos os SlackBuild's
END
	exit;
}
sub list {
	&banner() if $#ARGV<1;
	my $local = $ARGV[1];
	print `find $local -name *SlackBuild > .list`;
}
sub flags {
	open(FH, "<", ".list") || die ".list: $!\n";
	my @list = <FH>;
	close(FH);
	my $flags = $ARGV[1] || "-O2 -march=i686 -mcpu=i686";
	my $pwd = `pwd`;
	chomp($pwd);
	for my $file (@list){
		my $cwd = $file;
		chomp($file);
		$cwd =~ s/(.*\/).*$/$pwd\/$1/;
		next if ($file =~ /^#/ && $file !~ /^#!\/bin\/sh/);
		tie my @array, 'Tie::File', $file || die "$!\n";
		my $i = 0;
		for my $line (@array){
			$line =~ s/`pwd`/$cwd/ if $line =~ /^CWD=/;
			$line =~ s/i.86/i686/;
			$line =~ s/(.*\.\/(C|c)onfigure)(.*)/$1 CFLAGS="$flags" CXXFLAGS=\$CFLAGS$3/;
			@array[$i] = $line;
			$i++;
		}
	}
}
sub compiling {
	if($ENV{USER} ne 'root'){die "É necessário previlégios root!\n"}
	open(FH,"<",".list") || die ".list: $!\n";
	while(<FH>){
		next if /^#/;
		system("sh $_");
		print "\nOK!!!\n";
		print `play /opt/kde/share/sounds/Kopete_User_is_Online.ogg`;
		sleep(3);
	}
}
if($ARGV[0] eq '-l'){
	&list();
}elsif($ARGV[0] eq '-s'){
	&flags();
}elsif($ARGV[0] eq '-c'){
	&compiling();
}else{
	&banner();
}
