#!/usr/bin/perl -I/opt/SUNWstade24/lib
use Email;

# Takes 1 argument. Argument 1 is the directory where the persistence queue exists.

if($#ARGV != 0)
{
 print "Usage: emailIS.pl persistenceQueueDir\n";
 exit 1;
}

$| = 1;

$outputDir = $ARGV[0];

@list         = split(/\//, $outputDir);
$IRIS         = "/net/ha-ade/global/ha-nfs01/data/incoming/";
$irisDir      = $IRIS . $list[$#list];
$TIME         = time;

$filename     = "$outputDir/$TIME.$$";
$ncdfilename  = $filename.".toc";
$irisfilename = "$irisDir/$TIME.$$.toc";


# Read from STDIN until the end of the email header.
# First empty line is the end of the header.

my($in, $message);

while ($l = <STDIN>) {
  $all_message .= $l;
  if ($l =~ /Subject: secureTOC: \[(.+)\]/) {
     $hostid=$1;
  } elsif ($l =~ /^$/) {
     $in = 1;
  } elsif ($in) {
     $message .= $l;
  }
}
if ($hostid) {
  $key = `/apps/nscc/tools/make_key -h $hostid`;
  chop($key);
}

# debug for crypt
#`/bin/rm /tmp/secure/*`;
#open(O, ">/tmp/secure/raw_$$");
#print O "hostid=$hostid, key=$key \n$all_message";
#close(O);

my($sig, $decrypt) = Email->decrypt_email($message, $key);

#open(O, ">/tmp/secure/$$");
#print O $decrypt;
#close(O);

open(MSG,">$filename");
print MSG $decrypt;
close(MSG);

chmod(0777,$filename);

# Change the filename so that it has the ".ncd" extension and thus can be
# consumed by the Repository Manager.

if (open(O, ">$IRIS/OPEN/touch") ) {
   close(O);
   system("/bin/cp $filename $irisfilename");
}


rename($filename,$ncdfilename);

