#!/usr/bin/perl

# Copyright 2002 by Eric House
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

use strict;

use CGI qw/:standard *table  :html3/;
use File::Basename;

my $debug = 0;
my $q = new CGI;

die "wrong number of params\n" if $q->param() != 2;
my $filename = $q->param('file');
die "no file name param\n" if !$filename;

my $count = $q->param('count');
die "no count param\n" if !$count;
die "count $count bogus\n" if $count < 0;

if ( $count > 100) { 
    errorpage( "timeout: count $count too big" ); 
    exit 0;
} elsif ( -s $filename ) {
    returnFile( $filename );
    exit 0;
}

my $newQ = new CGI($q);
$newQ->param( 'count', $count+1 );

my $urlstr = $newQ->self_url();
print STDERR $urlstr, "\n" if $debug;

my $elapsedTime = 10 * $count;
print header, 
    start_html(-head=>meta({-http_equiv => 'refresh',
                            -content    => "10;URL=$urlstr" }),
               -title=>"A Simple Example"),

    h2("Preparing file \"" . basename($filename). "\""),

    p("The server is currently preparing the file " .
      basename($filename) . " for download to your computer.  This
      page will appear, with occasional changes in the paragraph
      below, until the file is ready.  When the file is ready the
      download will begin."),

    p( "$elapsedTime seconds (roughly) have passed so far.  If more
    than five minutes (300 seconds) elapse the server will abort and
    you'll see an error page here."),

    end_html;


##############################################################################
# subroutines

sub errorpage($) {
    my ( $str ) = @_;

    print header,
    start_html( "Error" ),
    p( $str ),
    end_html;
}


sub returnFile {
    my ( $filename ) = @_;

    die "file not found\n" if ! -s $filename;

    print header(-type=>'application/x-zip', -attachment=>basename($filename));

    open ZIPFILE, "< $filename";
    while ( my $nBytes = read( ZIPFILE, my $buffer, 1024 ) ) {
        print $buffer;
    }
    close ZIPFILE;
} # returnFile
