#!/usr/bin/perl
# file: record_to_tarball.pm	G. Moody         16 March 2009
#				Last revised:	  25 May 2016
# _____________________________________________________________________________
# record_to_tarball module for PhysioBank's Automated Teller Machine
# Copyright (C) 2009-2010 George B. Moody

use File::Basename;

sub mod_record_to_tarball {
    # Set the path, URL, and final output filenames for this request.
    $ubase = "/atm/$database/$record/export";
    $pbase = "/ptmp$ubase";
    $orec = basename($record);
    $ptar = "$pbase/$orec.tar.gz";
    $ptoc = "$ptar.toc";
    $utar = "$ubase/$orec.tar.gz";

    # If results for this request are already in the cache, return them.
    if (-s $ptoc && -s $ptar) {
	mod_record_to_tarball_out();
	return;
    }

    # Make sure the output has a place to go.
    mkpath($pbase);
    $ttar = "$ptar.$$";
    $ttoc = "$ptoc.$$";

    unless (fork) {
	open(STDOUT, ">$ttoc");
	chdir("/home/physionet/html/physiobank/database/$database");
	exec "$TAR cfvz $ttar $record*";
    }

    # Wait until tar is finished.
    wait;

    if (-s $ptoc) {  # there was a race, and this process lost!
	unlink($ttar);
	unlink($ttoc);
    }
    else {
	rename($ttar, $ptar);
	rename($ttoc, $ptoc);
    }
    mod_record_to_tarball_out();
}

sub mod_record_to_tarball_out {
    if (-s $ptoc) {
	$tsize = -s $ptar;
	print "Download <a href=$utar><tt>$orec.tar.gz</tt></a>",
	      " ($tsize bytes).  Once you",
	      " have completed the download, unpack the tarball by running the",
	      " command:<pre>tar xfvz $orec.tar.gz</pre>",
	      " This command unpacks the contents of the tarball into the",
	      " current directory.",
	      "<p>The contents of <tt>$orec.tar.gz</tt> are listed below:",
	      "<hr><pre>";
	show_file($ptoc);
	print "</pre>";
    }
    else {
	print "A tarball of $database/$record could not be made.  Please",
              " go <a href=/physiobank/database/$database>here</a> to download",
	      " the individual files of record $record.";
    }
}

1;
