#!/home/csoft/freebsd48/bin/perl
eval ' exec /home/csoft/freebsd48/bin/perl -S $0 "$@" '
	if $running_under_some_shell;
	shift if(join("", @ARGV) eq ""); # Xenix Kludge

use File::Basename;
my ($progname, $dirname) = fileparse($0); # save this very early
chop($dirname);

$USAGE = "
#
#   Usage: $progname [-v] [-e var=value]
#
# Options   Argument    Description
#   -b                  Use /bin/rpm
#   -d                  Generate defines
#   -v                  Verbose
#
";

sub usage {
	die join("\n",@_) .
	"\n$USAGE\n";
}
# This is in the prototype because it's frequently fiddled on a
# case by case basis for local debugging.
sub run {
	my $cmd = shift;
	print STDERR "system($cmd)" if $verbose;
	system($cmd);
}
# do "getopts.pl";

use strict;

use Getopt::Long;
# this uses the deprecated version so that it will work on older
# versions of perl5.
Getopt::Long::config qw {require_order bundling};

# declare global variables
use vars (
	'%opt_e',			# environment settings
	'$opt_h',			# print help
	'$opt_v',			# Verbose
	'$verbose',
	'$opt_d',
	'$opt_b',
);
usage("Invalid Option") unless GetOptions (
	'-e=s%',			# environment variables
	'-h|help',
	'-v|verbose',
	'-d|defines',
	'-b|binrpm',
);
for (keys %opt_e) {
	$ENV{$_} = $opt_e{$_};
}
$verbose = '-v' if $opt_v;
my $suffix = $$ unless $opt_v;

sub un_taint {
	my $PATH = $ENV{'PATH'};
	$ENV{'PATH'} = $PATH;
	$> = $<;	# make it ignore taintedness (
	$) = $(;	# gids )
}
# &un_taint();	# make it ignore taintedness

use Config;

$\ = "\n";	# use newlines as separators.

my $l_prefix = $Config{'prefix'};
my $opkgrpm = $l_prefix . q(libexec/openpkg/rpm);

my $rpmcmd = ( $opt_b || ! -x $opkgrpm ?  q(/bin/rpm) : $opkgrpm );

# get all installed RPMS if no argument specified
unless(@ARGV) {
	@ARGV = map {chomp; $_} (sort qx($rpmcmd -qa --qf='%{NAME}\n'));
}
my @outlines;
for my $rpm (@ARGV) {
	open(RPM, qq($rpmcmd -qi $rpm |));
	my $found_provides = 0;
	print STDERR "checking $rpm..." if $verbose;
	while(<RPM>) {
		next unless($found_provides || /^Provides/);
		$found_provides = 1;
		chomp;
		next unless(/^\s+(${rpm}::\S+) = (.*)/);
		my ($module, $state) = ($1, $2);
		if($opt_d) {
			$module =~ s/^${rpm}:://;
			push(@outlines, qq(\t--define '$module $state' \\));
		}
		else {
			push(@outlines, qq(-D $1=$2));
		}
	}
}
print join(qq(\n), (sort @outlines));
