#!/bin/bash

keyFile=./avida-key.pem

# Choose a validity period
VALIDITY_MINUTES=30

# Set timestamps
IAT=$(date -u +"%s")

if [ "$(uname)" = "Linux" ]; then
    EXP=$(date -u -d "+${VALIDITY_MINUTES} minutes" +"%s")
    NBR=$(date -u -d "-1 minute" +"%s")
else
    EXP=$(date -u -v+${VALIDITY_MINUTES}m +"%s") 
    NBF=$(date -u -v-1m +"%s")
fi

function b64enc() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; }

# Create a uuid for JTI
jti=$(uuidgen)

# Read payload.json, and replace the timestamp markers and jti in the payload
actual_payload=$(sed -E "s/%%%IAT%%%/${IAT}/" < payload.json)
actual_payload=$( echo -n ${actual_payload} | sed -E "s/%%%NBF%%%/${NBF}/")
actual_payload=$( echo -n ${actual_payload} | sed -E "s/%%%EXP%%%/${EXP}/")
actual_payload=$(echo -n ${actual_payload} | sed -E "s/%%%JTI%%%/${jti}/")

# base64url encode header and payload
header=$(cat header.json | b64enc)
payload=$(echo -n "$actual_payload" | b64enc )

# Combine the two into a message
message="${header}.${payload}"

# Create a signature over the message with the keyfile, and base64url encode
signature=$( echo -n $message | openssl dgst -sha256 -binary -sign $keyFile | b64enc )

# Combine all of the three into a valid JWT
jwt="$message.$signature"

echo "$jwt"
