#!/usr/bin/perl -w
# script to read a cdrom at the host system that was written with cdarchive.
# algorithm:
#   $ARGV[0] must be serial number of cdrom
#   mount the cdrom if necessary
#   copy and index newer archive/images to user/images
#   copy newer archive/userlogs to user/logs
#   copy newer archive/logs to archive/logs
#   copy and index newer user/images to user/images
#   copy newer user/logs to user/logs
#   index (but do not copy) newer archive/calib
#   index (but do not copy) newer archive/photcal
#   index (but do not copy) newer archive/pointmesh
#   copy BURNED file to archive/logs
#   unmount cdrom if we mounted it
#   run distemail if desired

# must be group talon
`id -gn` =~ /talon/ or die "Use newgrp talon\n";

# keep stdout in sync with stderr
$| = 1;

# need TELHOME
die "No TELHOME\n" if (!defined($ENV{TELHOME}));
$telhome = $ENV{TELHOME};

# minimum KB required on target filesystem
$minkb = 700000;

# index file; create its dir if necessary
$idxfn = "image_idx.lis";		# index file name
$idxdir = "$telhome/archive/db";	# index dir
$idxpn = "$idxdir/$idxfn";		# full path name
system "mkdir -p $idxdir" unless (-e $idxdir);

# first arg must be serial #, no spaces
$serial = $ARGV[0];
if (!defined($serial) or $serial =~ / / or $serial =~ /^-/) {
    $_ = $0; s#.*/##;
    print "Usage: $_ id\n";
    print "Purpose: receive a CDROM into the tracking system.\n";
    print "Writes files newer on CDROM to $telhome.\n";
    print "Updates index information in $idxpn.\n";
    print "Can also run distemail when finished if desired.\n";
    print "Arguments:\n";
    print "  id: serial number on CDROM; required, no spaces allowed\n";
    exit 1;
}

# confirm
print "$serial ? (y/n) [y] ";
sysread STDIN, $ans, 1000;
$ans !~ /n/ or die "Effort abandoned\n";

# ask whether to run distemail when finished -- capture time now
print "run distemail when finished? (y/n) [y] ";
sysread STDIN, $ans, 1000;
$rundistemail = $ans !~ /n/ ? time() : 0;

# make fixed-width for easier parsing of index
$serial = sprintf "%-10s", $serial;

# cdrom
$cdbase = "/mnt/cdrom";

# path to more goodies
$ENV{PATH} .= ":$telhome/bin";

# mount cdrom if not already
`mount | grep -q cdrom`;
if ($we_mounted = $?) {
    print "mounting $cdbase\n";
    system "mount $cdbase";
    die "Can not mount $cdbase\n" if ($? != 0);
    $SIG{'INT'}  = \&handler;
}

# print when cd was burned, copy to archive/logs
$_ = <$cdbase/BURNED.*>;
if (!defined($_)) {
    system "umount $cdbase" if ($we_mounted);
    die "No BURNED code\n";
}
system "cp $_ $telhome/archive/logs";		# copy off
/BURNED.([\d]+)/;				# extract the timestamp
print "CDROM was created " . `jd \`jd $1\``;	# show as UNIX date

# perform the copies
&copyem ("$cdbase/archive/userlogs", "$telhome/user/logs");
&copyem ("$cdbase/archive/images", "$telhome/user/images");
&copyem ("$cdbase/archive/logs", "$telhome/archive/logs");
&copyem ("$cdbase/user/logs", "$telhome/user/logs");
&copyem ("$cdbase/user/images", "$telhome/user/images");

# perform the index-only searches
&indexem ("$cdbase/archive/calib");
&indexem ("$cdbase/archive/photcal");
&indexem ("$cdbase/archive/pointmesh");

# maybe run distemail
$age = (time() - $rundistemail)/3600;	# it wants hours
system "distemail $age" if ($rundistemail > 0);

# finished
system "umount $cdbase" if ($we_mounted);
exit 0;

# copy newer stuff in $from to $to.
# then add to idxpn if not already there.
sub copyem
{
    my ($from, $to) = @_;
    my ($cmd);

    # silently do nothing if from does not exist
    return if (! -e $from);

    # check for space
    if (&kbleft($to) < $minkb) {
	print "Need at least $minkb KB on $to\n";
	return;
    }

    # report
    print "Copying $from to $to\n";

    # build up the shell command to do it all
    $cmd  = " cd $from;";		# set . to from
    $cmd .= " find . -print";		# find the files
    $cmd .= " | cpio -pd $to";		# copy if newer
    $cmd .= " > /dev/null 2>&1";	# very quietly

    # run it
    system "$cmd";

    # add new FITS files to index
    &indexem ($to);
}

# add index of FITS files off $dir, if not already
sub indexem
{
    my ($once) = 0;
    my ($dir) = @_;

    # silently do nothing if dir does not exist
    return if (! -e $dir);


    foreach my $pn (`find $dir -name '*.ft[sh]' -print`) {
	if (!$once) {
	    print "Indexing $dir\n";
	    $once = 1;
	}
	chomp($pn);
	$_ = $pn; s#.*/##;
	if (!&inindex($_)) {
	    system "fitshdr -P $pn | awk '{print \"$serial \" \$0}' >> $idxpn";
	}
    }
}

# return true if a name is already in the index
# ignores suffix (.fth or .fts)
sub inindex
{
    my ($name) = $_[0];

    # read existing filename entries into $havenow once
    if (!defined($havenow) and -r $idxpn) {
	$havenow = `awk '{printf \"#%s#", \$2}' $idxpn | sort -u`;
    }

    $name =~ s#\.ft.##;			# hack off suffix in query
    $havenow =~ /#$name\.ft[sh]#/;	# allow either suffix in match
}

# come here is get SIGINT
sub handler
{
    system "umount $cdbase" if ($we_mounted);
    exit 1;
}

# return number of kb left at path $_[0]
sub kbleft
{
    `df -k $_[0] | awk '/dev/ {print \$4}'` + 0;
}

# For RCS Only -- Do Not Edit
# @(#) $RCSfile: cdrcv,v $ $Date: 2003/04/15 20:47:55 $ $Revision: 1.1.1.1 $ $Name:  $
