#!/usr/bin/perl -w

# TODO check ret status of various stuff

use FileHandle;

sub my_system
{
    my (@cmds) = @_;
    foreach $cmd (@cmds) {
	my 	$ret =  ( system ($cmd))/256;
	if ($ret) {
	    print STDERR "\nmake_website: failed on command \`$cmd\' (status $ret)\n";
	    exit 2;
	}
    }
}

sub set_hrefs
{
    while (<HTMLIN>) {
	s#href=([A-Za-z.]+)#href=$base/$1#g;
	print HTMLOUT $_;
    }
}

sub all_refs
{
    print "resetting refs.\n";

    foreach $a (<*.html>)
    {
	rename $a, "$a~";
	open HTMLIN, "$a~";
	open HTMLOUT, ">$a";
	set_hrefs;
    }
}

local $base="lilypond/";
local @examples=("wohltemperirt" ,"standchen", "scsii-menuetto", "rhythm", "collisions");


sub gen_html
{
    print "generating HTML\n";
    my_system "make -kC .. html";
}

sub gen_examples
{
    print "generating examples: \n";
    foreach $a (@examples) {
	$texfile="lelie";
	$tex = "tex $texfile";
	if ($a eq "standchen" || $a eq "scsii-menuetto" ) {
	    $tex = "latex $a";
	    $texfile = "$a";
	}
	
	if ( ! -f "$a.ly.txt" ) {
	    my_system "ln $depth/input/$a.ly ./$a.ly.txt";
	}
	if ( ! -f "$a.ps.gz" ) {
	    my_system "lilypond $a;",
	    "$tex",
	    "dvips -o $a.ps $texfile;";

	}
	# generate the pixmap at twice the size, then rescale (for antialiasing)
	if ( ! -f "$a.gif" ) {
	    my_system "mv lelie.midi $a.midi; ",
	     "gs -q -sDEVICE=ppmraw -sOutputFile=- -r200 -dNOPAUSE  $a.ps -c quit |pnmscale 0.5| ppmtogif > $a.gif",
	     "gzip $a.ps";
	}   
    }
}


sub gen_list
{
    print "generating HTML list\n";
    open HTMLLIST, ">example_output.html";
    print HTMLLIST "<title>LilyPond examples</title>\n";
    foreach $a (@examples) {
	$name=$a;
	print HTMLLIST "<h1>example file: $name</h1>\n<XMP>\n";

	open IF, "$depth/input/$a.ly";
	input_record_separator IF "%}";
	
	$desc = <IF>;
	close IF;
	
	print HTMLLIST "$desc\n</XMP>";

	$inputf="$a.ly.txt";
	$giff="$a.gif";
	$psf="$a.ps.gz";
	$midif="$a.midi";
	
	print HTMLLIST "<ul>
<li><a href=$inputf> The input file</a>
<li><a href=$giff>The output (gif)</a>
<li><a href=$psf>The output (PS)</a>\n";
	
	print HTMLLIST "<li><a href=$midif>The output (MIDI)</a>\n"
	    if ( -f $midif );
	print HTMLLIST "</ul>";
    }
	close HTMLLIST;
}
sub copy_files
{  
    print "copying files\n";
    print `ln -s $depth/out ./docxx` if ( ! -x "docxx" ) ;
    my_system "cp $depth/TODO ./TODO.txt",
    "cp $depth/NEWS ./NEWS.txt",
    "cp ../lelie*gif .";
}

sub docxx_update
{
    my_system "make -C $depth doc++";
}

sub
    do_tar
{
     print "tarring.\n";
     my_system
	 " tar vhcf website.tar *.html *.gif *.ps.gz *.ly.txt *.midi docxx/*;",
	 "gzip -f9 website.tar;";
}

$depth = "../../";
$ENV{"TEXINPUTS"} .= ":$depth/input/:";
$ENV{"LILYINCLUDE"} = "$depth/input/";
my $cwd;
chomp($cwd = `pwd`);

die "need to be in directory Documentation\n" if ( ! ($cwd =~ /Documentation$/));
chdir ("out");


gen_html;
gen_examples;
gen_list;
copy_files;
docxx_update;
do_tar;
