#![cfg_attr(test, deny(warnings))]
#![deny(missing_debug_implementations)]
#[macro_use]
extern crate clap;
extern crate csr_gen;
extern crate openssl;

use std::io;
use std::io::prelude::*;
use std::fs::File;

use clap::Arg;

use openssl::pkey::PKey;

use csr_gen::Config;

fn main() {
    let matches = app_from_crate!()
        .arg(Arg::with_name("config")
                 .help("Configuration file to use for generating csrs")
                 .short("c")
                 .long("config")
                 .value_name("CONFIG")
                 .required(true)
                 .empty_values(false))
        .arg(Arg::with_name("stdin_key")
                 .help("Get the private key from standard input instead of file")
                 .short("s")
                 .long("stdinkey"))
        .get_matches();

    let mut f = File::open(matches.value_of("config").unwrap()).unwrap();

    let mut contents = String::new();
    f.read_to_string(&mut contents).unwrap();
    let contents = contents;
    let config = Config::from_str(&contents).unwrap();

    let mut contents = Default::default();
    if matches.is_present("stdin_key") {
        let stdin = io::stdin();
        let mut stdin = stdin.lock();
        stdin.read_to_end(&mut contents).unwrap();
    } else {
        let mut f = File::open(&config.key).unwrap();
        f.read_to_end(&mut contents).unwrap();
    };
    let key = PKey::private_key_from_pem(&contents).unwrap();

    config.generate_csrs(".", &key).unwrap();
}
