use warnings;
use strict;
use MIME::Base64;
use Digest::SHA qw(sha256);



my $aud=$ARGV[0];
my $sub=$ARGV[1];
my $exp=time+$ARGV[2];

my $s=encode_base64("{\"aud\":\"$aud\",\"sub\":\"$sub\",\"exp\":$exp}");
$s=~s/\n//g;
$s=~s/\+/\-/g;
$s=~s/\//_/g;

my $c=chop($s);
while ($c eq "="){ $c=chop($s); };
$s="eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.".$s.$c;


#print "$s\n";

my $s2=sha256($s);

my $fh;
open ($fh, ">:raw","tmp1.tmp");
print $fh $s2;
close($fh);

system("openssl pkeyutl -in tmp1.tmp -out tmp2.tmp -inkey vapid_private.pem -sign");

# according to RFC 7518 JSON Web Algorithms (JWA),
# we need exactly 64 bytes, but "openssl pkeyutl" made an asn.1 signature here

my $q=0;
open ($fh, "<:raw","tmp2.tmp");
read( $fh, $q, 2);

read( $fh, $q, 1);
read( $fh, $q, 1);
if (ord($q) == 33) { read ($fh,$q,1); };
read( $fh, my $p1, 32);

read( $fh, $q, 1);
read( $fh, $q, 1);
if (ord($q) == 33) { read ($fh,$q,1); };
read( $fh, my $p2, 32);
close($fh);


my $sig=encode_base64($p1.$p2);
$sig=~s/\n//g;
$sig=~s/\+/\-/g;
$sig=~s/\//_/g;

$c=chop($sig);
while ($c eq "="){ $c=chop($sig); };
$s="$s.".$sig.$c;

print "export jwt=$s\n";



