#!/usr/bin/env python3
import argparse
import base64
import hashlib
import json
import time

SHARED_KEY_DATA = b"kjfdlskfhiuewhfk947368"
SSH_RSA_KEY = "/etc/ssh/ssh_host_rsa_key.pub"


def read_server_id():
    with open(SSH_RSA_KEY, "rb") as f:
        return hashlib.md5(f.read()).hexdigest().upper()


def read_time():
    return time.time_ns() // (1000 ** 3)


def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("--key", default="pve8c-0000000000")
    parser.add_argument("--subscription", default="/etc/subscription")

    args = parser.parse_args()

    check_time = read_time()
    encoded_check_time = str(check_time).encode("utf-8")

    data = {
        "status": "active",
        "checktime": check_time,
        "serverid": read_server_id(),
        "key": args.key,
    }

    encoded_data = base64.b64encode(json.dumps(data).encode("utf-8"))

    checksum = hashlib.md5(encoded_check_time + encoded_data + SHARED_KEY_DATA)
    encoded_checksum = base64.b64encode(checksum.digest())

    subscription = b"\n".join(
        [args.key.encode("utf-8"), encoded_checksum, encoded_data]
    )

    with open(args.subscription, "wb") as f:
        f.write(subscription)


if __name__ == "__main__":
    main()