use std::io::{ Read, Write };
use std::fs::File;
use ring::digest;
use virt_enclave::sig::*;

fn main() {
    let mut args = std::env::args();
    args.next();
    let signing_key_pair = match SigningKeyPair::read_from_file("platform_signing_key.json") {
        Err(_) => { println!("Read file failed!"); return; },
        Ok(k) => k,
    };
    let f = match args.next() {
        None => { println!("File not assigned!"); return; },
        Some(f) => f,
    };
    let mut file = match File::open(&f) {
        Err(_) => { println!("Open file failed: {}", f); return; }
        Ok(f) => f,
    };
    let mut buf = vec![];
    let _len = match file.read_to_end(&mut buf) {
        Err(_) => { println!("Read file failed: {}", f); return; }
        Ok(c) => c,
    };
    let d = digest::digest(&digest::SHA256, &buf);
    let digest_hex = hex::encode(&d);
    let mut signed_message = SignedMessage::new(d.as_ref().to_vec(), None);
    signed_message.sign(&signing_key_pair);

    println!("File  : {}", f);
    println!("Hex   : {}", digest_hex);
    println!("Signed: {}", serde_json::to_string(&signed_message).unwrap());

    if let Some(of) = args.next() {
        if File::open(&of).is_ok() {
            println!("Output file exists: {}", of);
            return;
        }
        if let Ok(mut out_file) = File::create(&of) {
            out_file.write_all(&serde_json::to_string(&signed_message).unwrap().as_bytes()).ok();
            println!("Write file successed: {}", of);
        }
    }
}