#! /usr/bin/perl

use Foomatic::Defaults;

die "No \$libdir defined in Foomatic::Defaults!?"
    unless $libdir;

use Getopt::Std;
getopts("d:hk:l");
help() if $opt_h;

list() if $opt_l;

if (! -d $opt_k) {
    warn "No such directory `$opt_k'\n";
    help();
}


# OK, now sanity check and import
my $destdir = $opt_d;
my $dir = $opt_k;
if (!(-d "$dir/printer" or -d "$dir/driver" or -d "$dir/opt")) {
    die "No printer, driver, and/or opt directory in $dir; invalid kit?\n";
}

die "That's the library directory!\n"
    if ($dir =~ m"$destdir$libdir/db/source/?");

open FILES, "find $dir -type f -print |" 
    or die "Cannot run find!?";
while (<FILES>) {
    chomp;
    die "Non-xml file $_!\n"
	if (! m/\.xml$/);
}
close FILES or die "Cannot close pipe from find!";

# OK, we think it's valid now.

die "Foomatic library directory '$destdir$libdir/db' is not writable!\n"
    if (! (-d "$destdir$libdir/db" and -w "$destdir$libdir/db"));

my $retval = system("( cd $dir ; tar cf - . ) | tar xvCf $destdir$libdir/db/source - | tee $destdir$libdir/kitload.log");
$retval = $retval / 256;
if ($retval) {
    die "Error copying files to $destdir$libdir/db/source: $?";
}

sub list {
    print STDOUT "$libdir/db/source\n";
    exit(0);
}

sub help {
    print STDERR "Usage: foomatic-kitload -k kit-dir [-d destination prefix] [-l]\n";
    exit(0);
}


