#!/usr/bin/perl -w

use strict;

sub usage {
  print "ERROR: Usage: /opt/certVerify/cverify.pl !\n";
  exit -1;
}

sub subVar {
  my @keys = @_;
  my ($text, $parname, $var, $match);

  $text    = $keys[0];
  $parname = $keys[1];
  $var     = $keys[2];

  $match = "\\$parname";
  $text =~ s/$match/$var/g;
  return $text;
}

$SIG{INT} = sub {
        #local $SIG{TERM} = 'IGNORE';
  #print "uvatio0\n";   
   #print getppid();
 # kill TERM => -$$;
};


my $OPENSSL = "/home/globus/globus/bin/openssl";
my $HOME = `echo \$HOME`;
chomp($HOME);
my $CERT = $HOME . '/.globus/usercert.pem';
my $KEY = $HOME . '/.globus/userkey.pem';
#my $MSG = '/opt/certVerify/userCertConfirm.msg';

if (! -e $CERT){
  print "ERROR: Your certiricate is not installed in the .globus directory!\n";
  exit -1;
}

# get cert data
my $USR_DN = `$OPENSSL x509 -subject -noout < $CERT`;
chomp($USR_DN);
$USR_DN =~ s/subject= ?//;
$USR_DN =~ m/CN=((\w|\-|\s)+)/;
my $USR_NAME = $1;
my $CERT_SN = `$OPENSSL x509 -serial -noout < $CERT`;
chomp($CERT_SN);
$CERT_SN =~ s/serial= ?//;
$CERT_SN = hex($CERT_SN);
my $USR_MAIL = `$OPENSSL x509 -email -noout < $CERT`;
chomp($USR_MAIL);

#open(TMPL, $MSG) or die $!;
#my $msgtext = '';
#while (my $temp = <TMPL>) {
#  $msgtext .= $temp;
#}
#close TMPL;

my $msgtext = "
Dear SRCE CA Staff,

with this email I state that:

1. I, __USER__, accept my digital certificate with following data:
   DN: __CERT_DN__
   Serial Number: __CERT_SN__
   Issued by: /C=HR/O=edu/OU=srce/CN=SRCE CA

2. I adhere to the SRCE CA certificate policy:
   URL: http://ra.srce.hr/policy/policy.pdf
   OID: 1.2.840.113612.5.4.2.4.1.1.1

Best regards,
__USER__";

$msgtext = subVar($msgtext, '__USER__', $USR_NAME);
$msgtext = subVar($msgtext, '__CERT_DN__', $USR_DN);
$msgtext = subVar($msgtext, '__CERT_SN__', $CERT_SN);

my $filename = "/tmp/" . rand(1000000) . ".txt";
my $msg = "/tmp/" . rand(1000000) . ".msg";
open(TEMP, '>', $filename) or die $!;
print TEMP $msgtext;
close TEMP;

# send mail
my $to = 'hsute@srce.hr';
my $from = $USR_MAIL;
my $subject = 'SRCE CA Certificate Statement';
my $smime = `$OPENSSL smime -sign -inkey $KEY -signer $CERT -in $filename -from $from -to $to -subject "$subject" -nodetach -out $msg`;
if ($? == 0){
  my $send = `cat $msg \| /usr/sbin/sendmail $to`;
}
unlink($filename) || print $!;
unlink($msg) || print $!;

