#!/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;

print "Unesite podatke o zahtjevu i nakon toga pritisnite ENTER pa CTRL-D:\n";
my @inputxt = <STDIN>;
if($inputxt[0] !~ m/ADDITIONAL_ATTRIBUTE_ADDRESS/){
  print "Prva unesena linija mora pocinjati sa ADDITIONAL_ATTRIBUTE_ADDRESS. Probajte ponovno:\n";
  @inputxt = <STDIN>;
  if($inputxt[0] !~ m/ADDITIONAL_ATTRIBUTE_ADDRESS/){
    die('Pogledajte upute na: http://wiki.cro-ngi.hr/index.php/Rekey_korisni%C4%8Dkog_certifikata'."\n");
  }
}

my $msgtext = "\nDear SRCE CA Staff,\n
with this email I state that I submitted following request for rekeying of user certificate:\n\n";

foreach (@inputxt) {
  $msgtext .= $_;
}
$msgtext .= "\n\nBest regards,\n$USR_NAME";

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 = 'srce-ca@srce.hr';
my $from = $USR_MAIL;
my $subject = 'SRCE CA User Certificate Rekey Request Confirmation';
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 $!;

