#!/usr/bin/env python3

#   -------------------------------------------------------------
#   Renew Vault HTTPS certificates
#   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#   Project:        Nasqueron
#   Description:    Connect to Vault
#   License:        BSD-2-Clause
#   -------------------------------------------------------------


import hvac
import yaml
import json
import requests
import sys

from pprint import pprint


#   -------------------------------------------------------------
#   Certificates renewal
#   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


CERTIFICATES_FRAGMENTS = {
    "certificate": "certificate.pem",
    "issuing_ca": "ca.pem",
    "private_key": "private.key",
}

CERTIFICATES_FULLCHAIN = ["certificate", "issuing_ca"]


def renew_vault_certificates(client):
    extra_params = {
        "ttl": "2160h",
        "ip_sans": "127.0.0.1,172.27.27.7",
    }

    response = client.secrets.pki.generate_certificate(
        name='nasqueron-drake',
        common_name='complector.nasqueron.drake',
        mount_point='pki_vault',
        extra_params=extra_params,
    )

    certificate = response["data"]

    for key, certificate_file in CERTIFICATES_FRAGMENTS.items():
        with open(certificate_file, "w") as fd:
             print(certificate[key], file=fd)

    with open("fullchain.pem", "w") as fd:
        for key in CERTIFICATES_FULLCHAIN:
            print(certificate[key], file=fd)


#   -------------------------------------------------------------
#   Application entry point
#   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -


def run():
    client = hvac.Client(verify=False)

    renew_vault_certificates(client)


if __name__ == "__main__":
    run()