#!/usr/bin/env python3
'''
Python script to split stacked pem into cert+ca and secret.

az_script-01-git.manifest.sh installs python3 -m pip pem
'''
import pem
import sys
#import os

if len(sys.argv) != 3:
    print("Err: need two argument, pem file name. and base output file name + .pem/.key")
    sys.exit(1)

file_in = sys.argv[1]
f_out_base = sys.argv[2]
certs = pem.parse_file( file_in )
# for method in dir(object):
#     print("method:",method)
cnt_key = 0
cnt_cert = 0
with open(f"{f_out_base}.key", 'w') as fk, open(f"{f_out_base}.pem", 'w') as fc:
    for cert in certs:
        #print("cert:", cert, type(cert).__name__)
        if type(cert).__name__ == "PrivateKey":
            fk.write(cert.as_text())
            cnt_key +=1
        elif type(cert).__name__ == "Certificate":
            fc.write(cert.as_text())
            cnt_cert +=1
        else:
            print(f"Err: file {file_in} contained section of unkown type={type(cert).__name__} ")
            sys.exit(1)
# print()

print(f"created files with base {f_out_base}(.key|.pem), {cnt_key} key and {cnt_cert} certs")
if (cnt_key < 1) or (cnt_cert < 1):
    print("Error key or cert missing.")
    sys.exit(1)
print(f"The END. {sys.argv[0]}")
