# coding: utf-8


from datetime import datetime, timedelta
from inspect import getsource

from cryptography.hazmat.primitives.asymmetric.rsa import generate_private_key
from cryptography.hazmat.primitives.hashes import SHA256
from cryptography.hazmat.primitives.serialization import (
    Encoding,
    NoEncryption,
    PrivateFormat,
)
from cryptography.x509 import (
    CertificateBuilder,
    Name,
    NameAttribute,
    NameOID,
    SubjectAlternativeName,
    DNSName,
    random_serial_number,
)

pk = generate_private_key(key_size=2048, public_exponent=65537)

me = Name(
    [
        NameAttribute(NameOID.COMMON_NAME, "A Host, Locally"),
        NameAttribute(NameOID.COUNTRY_NAME, "TR"),
        NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Çorum"),
        NameAttribute(NameOID.LOCALITY_NAME, "Başmakçı"),
        NameAttribute(NameOID.ORGANIZATION_NAME, "Twisted Matrix Labs"),
        NameAttribute(NameOID.ORGANIZATIONAL_UNIT_NAME, "Automated Testing Authority"),
        NameAttribute(NameOID.EMAIL_ADDRESS, "security@twistedmatrix.com"),
    ]
)

certificate_bytes = (
    CertificateBuilder()
    .serial_number(random_serial_number())
    .not_valid_before(datetime.now())
    .not_valid_after(datetime.now() + timedelta(seconds=60 * 60 * 24 * 365 * 100))
    .subject_name(me)
    .add_extension(SubjectAlternativeName([DNSName("example.com")]), critical=False)
    .issuer_name(me)
    .public_key(pk.public_key())
    .sign(pk, algorithm=SHA256())
).public_bytes(Encoding.PEM)

privkey_bytes = pk.private_bytes(
    Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()
)

import __main__

source = getsource(__main__)
source = source.split("\n" + "-" * 5)[0].rsplit("\n", 1)[0]
with open("server.pem", "w") as fObj:
    fObj.write(source)
    fObj.write("\n")
    fObj.write('"""\n')
    fObj.write(privkey_bytes.decode("ascii"))
    fObj.write(certificate_bytes.decode("ascii"))
    fObj.write('"""\n')
with open(b"key.pem.no_trailing_newline", "w") as fObj:
    fObj.write(privkey_bytes.decode("ascii").rstrip("\n"))
with open(b"cert.pem.no_trailing_newline", "w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