#! /usr/bin/perl

use Getopt::Std;
getopts("hd");
help() if $opt_h;

use Foomatic::DB_perl_xml qw(grove_to_xml grove_pathval pretty_xml);
use Foomatic::PPD;
use Foomatic::Defaults;

my $file = $ARGV[0];
my $printer = $ARGV[1];

my $db = new Foomatic::DB_perl_xml;

if (! -f "$libdir/db/source/printer/$printer.xml") {
    die "Printer $printer does not seem to exist in the database!\n";
}

if (! -f $file) {
    die "The PPD file you specified, $file, does not seem to exist!\n";
}

# Load the PPD
my $p = new Foomatic::PPD $file, $printer;

if ($opt_d) {
    # Parser PPD structure dump
    use Data::Dumper;
    local $Data::Dumper::Purity=1;
    local $Data::Dumper::Indent=1;
    print Dumper($p);
} else {
    # Normal behavior, save as various option files by ID
    my @opts = $p->foo_options();
    for (@opts) {
	my ($id, $xml) = ($_->{'id'}, $_->{'xml'});

	my $ofile = "$libdir/db/source/opt/$id.xml";
	my $prettyxml;
	if (1) {
	    $prettyxml = pretty_xml(join('',@{$xml}));
	} else {
	    $prettyxml = join('',@{$xml});
	}
	open TMP, ">$ofile" or die;
	print STDERR "Writing $ofile\n";
	print TMP $prettyxml;
	close TMP;
    }

    # Add this printer to the ppd driver
    my $dgrove = $db->get_driver_grove("ppd");

    # Either we've got it already
    my $plist = $dgrove->at_path('/driver/printers');

    my $found = 0;
    my $elem;
    for $elem (@{$plist->{Contents}}) {
	next if ($elem->{Name} ne 'printer');

	if ("printer/$printer" eq grove_pathval($elem, '/id')) {
	    # it's here
	    $found = 1;
	}
    }

    # Or we need to append a new item and write the file
    if (! $found) {
	my $elem = new XML::Grove::Element(Name=>'printer');
	push(@{$elem->{Contents}}, 
	     new XML::Grove::Element(Name=>'id',
				     Contents=> [ new XML::Grove::Characters ( Data=>"printer/$printer" ) ] ));

	push (@{$plist->{Contents}},
	      $elem);

	print STDERR "Writing $libdir/db/source/driver/ppd.xml\n";
	$db->_set_object_xml('source/driver/ppd',
			     pretty_xml(grove_to_xml($dgrove)),
			     0);   # not cache!

    }

}

exit(0);

sub help {
    select STDERR;
    print "Usage: foomatic-ppdload filename.ppd printer-id\n";
    exit(1);
}
