#!/usr/bin/perl -w
#
# Install files required by publication in a directory; attempt to make
# publication painless
#
# Note that the specification already needs to be in good shape since we
# are not copying any Makefile
#
# Hugo Haas - 2003-07-25

use strict;
use XML::DOM;
use Getopt::Long;

my $xmlspec = 'wd-wsa-arch-review2.xml';
my @files;

# Get options
my %opts;
my $overwrite = 0;
GetOptions('o' => \$overwrite);

# Usage
if ($#ARGV < 0) {
    print STDERR "Usage: $0 [ -o ] <target directory>\n";
    exit(1);
}

my $targetdir = $ARGV[0];

if (! -d $targetdir) {
    &mymkdir($targetdir);
}

# Get list 
my $parser = new XML::DOM::Parser;
my $doc = $parser->parsefile($xmlspec);
my $nodes = $doc->getElementsByTagName('graphic');
my $n = $nodes->getLength;

for (my $i = 0; $i < $n; $i++) {
    my $node = $nodes->item($i);
    my $href = $node->getAttributeNode('source');
    print "Found image: " . $href->getValue() . "\n";
    push(@files, $href->getValue());
}

# Copy files
sub copy() {
    my ($source, $t) = @_;
    if (! defined($t)) {
	$t = $source;
    }
    my $target = $targetdir . '/' . $t;
    print "Copying $source to $target\n";
    if (-f $target) {
	if ($overwrite) {
	    print "Warning: overwriting $target as requested\n";
	} else {
	    print STDERR "Error: File $target already exists; stopping.\n";
	    print STDERR "Use -o option to overwrite files.\n";
	    exit(1);
	}
    }
    system('cp', '-v', '-f', $source, $target) == 0 || die "Error: $!\n";
}

sub mymkdir() {
    my ($d) = @_;
    if (-d $d) {
	print "$d already exists";
	return;
    }
    print "Creating $d directory\n";
    mkdir($d) || die "Error: $!\n";
}

my $htmlspec;
($htmlspec = $xmlspec) =~ s/\.xml$/\.html/;
&copy($htmlspec, 'Overview.html');
&mymkdir("$targetdir/images");
foreach my $f (@files) {
    &copy($f);
}
&copy('wsa.ps');
&copy('wsa.pdf');

print "Done.\n";
