#!/bin/bash

EXPIRATION=${EXPIRATION:-$(date -d '+1 month' '+%s')}

if [ -z "$SECRET_KEY" ]; then
    echo "SECRET_KEY environment variable is not set" >&2
    echo "SECRET_KEY must point to the file containing the secret key" >&2
    exit 1
fi
if [ -z "$SERVER_ID" ]; then
    echo "SERVER_ID environment variable is not set" >&2
    echo "SERVER_ID must contain a unique identifier for the server" >&2
    exit 1
fi

server_id="SS-CW-$(echo -n "$SERVER_ID" | sha256sum | awk '{print $1}' | head -c 50)"
status=ok
limit=2147483647
token_created_utc=$(date +%s)
token_expire_utc=$EXPIRATION

content="$server_id$status$limit$token_created_utc$token_expire_utc"
sign=$(echo -n "$content" | openssl dgst -sha512 -sign "$SECRET_KEY" | base64 -w 0)

printf "{\n\
    \"id\": \"$server_id\",\n\
    \"signatures\": [\"$sign\"],\n\
    \"sign\": \"$sign\",\n\
    \"group\": \"\",\n\
    \"status\": \"$status\",\n\
    \"limit\": $limit,\n\
    \"token_created_utc\": $token_created_utc,\n\
    \"token_expire_utc\": $token_expire_utc,\n\
    \"message\": \"\"\n\
}"
