#!/usr/bin/perl

use JSON;
use MIME::Base64;
use Crypt::OpenSSL::RSA;

use utf8;

print "Test 2\n";

# Lag en JWT request
# 1: Header
my $header = qq!{"alg":"RS256","typ":"JWT"}!;
my $encoded_header = encode_base64($header);

# 2: Claims
my $time = time();
my $exp  = $time + 3599;


my $claims = qq!{
  "iss":"kalendertest3@kalendertest-235300.iam.gserviceaccount.com",
  "scope":"https://www.googleapis.com/auth/devstorage.readonly",
  "aud":"https://www.googleapis.com/oauth2/v4/token",
  "exp":$exp,
  "iat":$time,
  "sub":"galemathias@gmail.com"
}!;

print "Claims: $claims\n";

my $encoded_claims =  encode_base64($claims);

# 3: Signer
my $rsa = Crypt::OpenSSL::RSA->new_private_key("-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDsRif3Jdmzg4nX
DG1Q1Qe0fzpx8YDv+jPn6iTWQnVQ1kMZu7tFNwT7XC35g+Lh3E5kX4rzQP7lIvBz
gMRbUVpp3Y5x/55ll5dDXICE+UQyHE696GnClfV3PlafHzx5EMUDIIsCjrV9OE8K
0asYWRarHBpCm2p1L73HPq2/qFiYi86NXRId4lNEl202tQJ6q+ABT/hOudV8rFeK
5T5TTkxkkiDa89FKSu2LK2AmJ1OTS1Zf/Y8FkMjL5Y2qLNggO/cYvSn6uJAYKrKr
s+45zdWwuq5t67Hc3NXw6TglNEyOnZ+mSd8m0HuuctRzDuo3E1+GtfhR+wdwNg5z
6DtnNQj/AgMBAAECggEAaEXx/13h/RqRK6odWG4bz2nS5lR53e7jF3e7OB/uXHWi
+WljlYFZnoEo/RRafelXY27TCNXnaEKKMb9jaRW3PD9+TQtN4XIMXLsnMQg9M4xQ
p/k5K5o40Z5eZi1H5/ohqGalUsSejhvarmCoDL/MhEmLwVeLnRorvBIKZioqp286
5CegHHVMTEX+TR2xQzPIt4Olb71s72OmV5RohJjAKbZnyC9CT7ub+y2CUsN6VKRn
PqgsYU7elBf79eMjvQu1y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= ($encoded_header . "." . $encoded_claims);
warn "1. sign: $sign\n";

$sign = $rsa->sign($sign);
warn "2. sign: $sign\n";

$sign = encode_base64($sign);
warn "3. sign: $sign\n";

my $jwt = ("$encoded_header" . "." . "$encoded_claims" . "." . $sign);
warn "jwt: $jwt\n";

print "curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt' https://www.googleapis.com/oauth2/v4/token\n";

# print $jwt;
my $token = `curl -d 'grant_type=urn%3Aietf%3Aparams%3Aoauth%3Agrant-type%3Ajwt-bearer&assertion=$jwt' https://www.googleapis.com/oauth2/v4/token`;

print "Token: $token";