#!/usr/bin/perl -w

use strict;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
my $cgi = new CGI;

# default front:
my $front = <<EOD
\\vspace{15mm}
\\begin{center}
\\huge \\bf

Title

\\end{center}
EOD
    ;

# default back:
my $back = <<EOD
\\vspace{8mm}
\\begin{center}
\\textbf{ Title }
\\vspace{5mm}

\\small
\\track[3:21]{Artist: Title}

\\end{center}
EOD
    ;

my $outfile = "cdcase.*"; 
my $thisfile =  $ENV{'SCRIPT_NAME'};
my $result;

print $cgi->header();

if ($cgi->param()) {
    $result = Process();
    # store oufile value:
    open(OUTF, ">.outfile");
    print OUTF $cgi->param('outfile');
    close(OUTF);
}
else {
    # restore previous oufile value:
    if (-e ".outfile") {
	open(OUTF, "<.outfile");
	while (my $content = <OUTF>) {
	    $outfile = $content;
	}
	close(OUTF);
    }
}

sub Process {
    $outfile = $cgi->param('outfile');
    $front = $cgi->param('front');
    $back = $cgi->param('back');

    open(TEMPL, "<template.tex") || return "<h2>Error: Could not open template.tex.</h2>";
    my @texlines = <TEMPL>;
    close(TEMPL);

    foreach (@texlines) {
	$_ =~ s/!front/$front/;
	$_ =~ s/!back/$back/;
    }

    my $outtex = substr($outfile,0,-1)."tex";
    open(TEXFILE, ">$outtex") || return "<h2>Error: Could not write $outtex.</h2>";
    print TEXFILE @texlines;
    close(TEXFILE);
    $_ = `latex $outtex`;
    if (!($_ =~ /output written/i)) {
	return "<h2>LaTeX Errors in <a href='$outtex'>$outtex</a></h2><pre>$_</pre>";
    }

    my $outdvi = substr($outfile,0,-1)."dvi";
    my $outps = substr($outfile,0,-1)."ps";
    $_ = `dvips $outdvi`;
    if ($_) {
	return "<h2>dvips Error: $_</h2>";
    }
    return "<h4>Result: <a href='$outps'>$outps</a>, <a href='$outtex'>$outtex</a></h4>\n";
}

print <<EOD

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>Print CD Case</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style type="text/css">
h2 a { text-decoration:none; }
body { margin:2em; font-family:sans-serif; }
label { display:block; margin:1em 0 0 0; font-weight:bold; }
</style>
</head>
<body>

<h2><a href='$thisfile'>Paper CD Case</a></h2>

$result

<form action='$thisfile' method='GET'>

<label for='outfile'>Output to:</label>
<input type='text' size='70' id='outfile' name='outfile'
value='$outfile'><br>
Relative location, .* = .tex/.ps


<label for='front'>Front (minipage 12x12cm):</label>
<textarea rows='12' cols='70' name='front' id='front' wrap='off'>
$front
</textarea>
<br>


<label for='back'>Back (minipage 12x12cm):</label>
<textarea rows='12' cols='70' name='back' id='back' wrap='off'>
$back
</textarea>
<br>
<br>

<input type="submit" value="Create CD Case">

</form>

</html>

EOD
    ;
