#!/usr/bin/perl
use strict;
use IO::File;
use Getopt::Std;
use vars qw($opt_c);

# FIXME: someday just replace this with 
# autoconf and configure. that's really the 
# standard way to go about doing these things
# you can certainly keep the structure of the existing 
# makefiles, all you need is to define some variables

getopts ("c");
our $CMDLINE = defined $opt_c;

my %CONF_SETTINGS = (
    "check debian-ness" => \&CheckDebian,
    "check existence of libunwind" => \&CheckLibUnwind,
);

sub CheckDebian {
    my $grep = `cat /etc/issue | egrep 'Ubuntu|Debian'`;
    chomp ($grep);

    if ($grep ne "") { 
	return "#define DEBIAN";
    }
    else {
	return "#undef DEBIAN";
    }
}

sub CheckLibUnwind {
    my @dirs = ('/usr/local/lib', '/usr/lib');
    foreach my $dir (@dirs) {
	if (-f "$dir/libunwind.so") {
	    return "#define HAVE_LIBUNWIND";
	}
    }
    return "#undef HAVE_LIBUNWIND";
}

my $config = "config.h";
my $f;

if ($CMDLINE) {
    $f = new IO::File ("> /dev/stdout");
}
else {
    $f = new IO::File ("> $config");
}

if (not defined $f) { 
    print STDERR "* Could not open $config for writing!\n";
    exit 1;
}

print $f "#ifndef CONFIG__H\n#define CONFIG__H\n\n";
foreach my $key (keys %CONF_SETTINGS) { 
    my $func = $CONF_SETTINGS {$key};
    my $string = &$func ();
    print $f "/* $key */\n$string\n\n";
}
print $f "\n#endif // CONFIG__H\n";

close ($f);

