use std::io::Read;
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 sf = match args.next() {
        None => { println!("Sign 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 sign_file = match File::open(&sf) {
        Err(_) => { println!("Open sign file failed: {}", sf); 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 mut sign_buf = vec![];
    let _sig_len = match sign_file.read_to_end(&mut sign_buf) {
        Err(_) => { println!("Read file failed: {}", sf); return; }
        Ok(c) => c,
    };
    let signed_message = match serde_json::from_str::<SignedMessage>(&String::from_utf8(sign_buf).unwrap()) {
        Err(_) => { println!("Parse sign file failed: {}", sf); return; }
        Ok(m) => m,
    };
    let d = digest::digest(&digest::SHA256, &buf);
    let matches  = d.as_ref().to_vec() == signed_message.msg.clone();

    let digest_hex = hex::encode(&d);
    let msg = &signed_message.msg;

    println!("File  : {}", f);
    println!("Hex   : {}", digest_hex);
    println!("SHex  : {}  - {}", hex::encode(msg), if matches { "matches"} else { "NOT matched" });
    println!("Signed: {}", signed_message.verify(&signing_key_pair.public_key()));
}