/// <reference path="../../../typings/tsd.d.ts" />
/**
 *              NewKeyPair
 *      @param email                <string>        email address
 *      @param name                 <string>        name
 *      @param keyBitLength         <string>        key bit length
 *      @param password             <string>        password
 */
import * as openpgp from 'openpgp';
import * as fs from 'fs'
import * as Async from 'async';
import * as path from 'path';
import * as osenv from "osenv";

const setupFolderName = '/Vpn.Email'
const localPath = path.parse ( osenv.home() + setupFolderName )

const cer_PrivfileName = path.parse(path.format(localPath)+'/systemCerPriv.key.pem')
const cer_PubfileName = path.parse(path.format(localPath)+'/systemCerPub.key.pem')
const env: IKeyInformation = process.env;
console.log (env)
const NewKeyPair = ( email: string, name: string, keyBitLength: string, password: string ) => {

    const userId = {
		name: name,
		email: email }

    const option = {
        numBits: parseInt ( keyBitLength ? keyBitLength : '1024' ),
        passphrase: password,
        userIds: userId
    }
    
    openpgp.generateKey ( option ).then (( keypair ) => {
        // success
        
		fs.writeFileSync ( path.format ( cer_PrivfileName ), keypair.privateKeyArmored, { encoding: 'utf8' });
		fs.writeFileSync ( path.format ( cer_PubfileName ), keypair.publicKeyArmored, { encoding: 'utf8' });
		process.exit ( 0 )

    }).catch (( err: Error ) => {
        // ERROR
		console.log ( err )
        process.exit ( 1 )
        
    })
}

NewKeyPair ( env.email, env.userName, env.keyBitLength.toString(), env.keyPassword );
