No stamp files were found for the specified set of detections. Sorry.

<%args>
$det_ids
$prefix => 'stamp'
$eq => 1
</%args>

<%init>
use Digest::MD5;
use File::Temp;
use File::Slurp;
use PS::MOPS::DC::Detection;

my $inst = $m->notes('INST');
my $dbname = $inst->dbname;
unless (ref($det_ids)) {
    $det_ids = [ $det_ids ];    # convert Mason single item to list
}

my $dfile;
my $cfile;
my @files;
foreach my $det_id (@{$det_ids}) {
    my $det = modcd_retrieve($inst, detId => $det_id) or die "can't get det $det_id";
    my $id = sprintf "%010d", $det_id;
    my $nn = int($det->epoch) - 1;  # TJD to MOPS nn
    my $dreldir = join('/', 'MD', split '', substr(uc(Digest::MD5::md5_hex($id)), 0, 5));
    my $creldir = join('/', 'MC', split '', substr(uc(Digest::MD5::md5_hex($id)), 0, 5));

    $dfile = $inst->getEnvironment('VARDIR') . "/stamps/$dreldir/MD-$id.fits";
    if (!-f $dfile) {
        my ($dir) = $det_id =~ /(\d)$/;
        $dfile = "/data/mops13.0/stamp-store/stamps/special-stamps/$dbname-auto/$nn/$dir/D$det_id.fits";
        if (!-f $dfile) {
            $dfile = "/data/mops13.0/stamp-store/stamps/special-stamps/$dbname-auto/$nn/D$det_id.fits";
        }
    }
    my $have_dfile = -f $dfile;

    $cfile = $inst->getEnvironment('VARDIR') . "/stamps/$dreldir/MC-$id.fits";
    if (!-f $cfile) {
        my ($dir) = $det_id =~ /(\d)$/;
        $cfile = "/data/mops13.0/stamp-store/stamps/special-stamps/$dbname-auto/$nn/$dir/C$det_id.fits";
        if (!-f $cfile) {
            $cfile = "/data/mops13.0/stamp-store/stamps/special-stamps/$dbname-auto/$nn/C$det_id.fits";
        }
    }
    my $have_cfile = -f $cfile;

    if ($have_cfile) {
        push @files, $cfile;
    }
    elsif ($have_dfile) {
        push @files, $dfile;
    }

}

# Must be at least one existing file.
if (@files) {
    my $dir = File::Temp::tempdir('/tmp', 'stampdir.XXXXXXXX', CLEANUP => 1);
    my $zipfile = "$prefix.zip";
    system('zip', '-qj', "$dir/$zipfile", @files) == 0 or die "can't create ZIP file $dir/$zipfile";


    my $stuff = read_file("$dir/$zipfile");
    $r->content_type('application/zip');
    $r->headers_out->add('Content-Disposition' => "filename=$zipfile");
    $m->clear_buffer;
    $m->print($stuff);
    $m->abort;
    File::Temp::cleanup();
}
</%init>
