import hmac
import hashlib
import base64
import json
import time
import os
import sys

if len(sys.argv) != 2:
    print("usage: python3 gen-jwt.py <jwt_secret>", file=sys.stderr)
    sys.exit(1)

secret = sys.argv[1]
b = lambda d: base64.urlsafe_b64encode(d).rstrip(b"=").decode()
iat = int(time.time())
exp = iat + 315360000  # 10 years

for role in ["anon", "service_role"]:
    h = b(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
    p = b(json.dumps({"role": role, "iss": "supabase", "iat": iat, "exp": exp}, separators=(",", ":")).encode())
    s = b(hmac.new(secret.encode(), (h + "." + p).encode(), hashlib.sha256).digest())
    print(role + ": " + h + "." + p + "." + s)
