
import {
    default as forge
} from "node-forge";

import {
    readFileSync,
    writeFileSync,
    mkdirSync
} from "fs";


export function loadCertificate(sCertID) {
    return forge.pki.certificateFromPem(
        readFileSync(`datastore/certificates/${sCertID}/certificate.pem`, 'utf8')
    );
}

export function loadPrivateKey(sCertID) {
    return forge.pki.privateKeyFromPem(
        readFileSync(`datastore/certificates/${sCertID}/privateKey.pem`, 'utf8')
    );
}


export function saveCertificate(iCertificate, sCertID, sCertType) {
    // encode certificates as PEM
    const certificate = forge.pki.certificateToPem(iCertificate);

    // create certificate directory
    mkdirSync(`datastore/certificates/`, { recursive: true });

    // write certificate to file
    writeFileSync(`datastore/certificates/${sCertID}.crt`, certificate);
}

export function savePrivateKey(iPrivateKey, sCertID) {
    // encode keys as PEM
    const privateKey = forge.pki.privateKeyToPem(iPrivateKey);

    // create key directory
    mkdirSync(`datastore/keys/`, { recursive: true });

    // write keys to file
    writeFileSync(`datastore/keys/${sCertID}.key`, privateKey);
}


export function generatePublicKeyFromPrivateKey(iPrivateKey) {
    return forge.pki.rsa.setPublicKey(iPrivateKey.n, iPrivateKey.e);
}