use rcgen::{CertificateParams, DnType, DnValue, KeyPair};
use std::error::Error;
use std::{
    fs::{File, Permissions},
    io::Write,
    os::unix::prelude::PermissionsExt,
    path::PathBuf,
};

pub fn gen_cert(
    subject_alt_names: Vec<String>,
    cert_path: &PathBuf,
    key_path: &PathBuf,
) -> Result<(), Box<dyn Error>> {
    let subject_name = subject_alt_names.first().unwrap().clone();

    let mut params = CertificateParams::new(subject_alt_names)?;
    params
        .distinguished_name
        .push(DnType::CommonName, DnValue::Utf8String(subject_name));

    let key_pair = KeyPair::generate().unwrap();

    let cert = params.self_signed(&key_pair)?;

    // Write cert
    let pem = cert.pem();
    let mut file = File::create(cert_path).unwrap();
    write!(file, "{pem}")?;

    // Write key
    let mut file = File::create(key_path)?;
    file.set_permissions(Permissions::from_mode(0o600))?;
    write!(file, "{}", key_pair.serialize_pem())?;

    Ok(())
}
