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

fn main() -> XResult<()> {
    let mut args = std::env::args();
    args.next();
    let signing_key_pair = virt_enclave::util::load_signing_key_pair().expect("Load singing key pair!");
    let f = args.next().ok_or_else(|| rust_util::new_box_error("File not assigned!"))?;
    let mut file = File::open(&f)?;
    let mut buf = vec![];
    file.read_to_end(&mut buf)?;
    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);

    let js_path = Path::new("js");
    if !js_path.exists() {
        std::fs::create_dir(js_path).expect("Create js/ dir");
    }

    let js_file = format!("js/{}.js", digest_hex);
    let js_sign_file = format!("js/{}.sig.json", digest_hex);

    File::create(&js_file)?.write_all(&buf).expect("Write js/HEX.js file");
    println!("Write file successed: {}", js_file);
    File::create(&js_sign_file)?.write_all(serde_json::to_string(&signed_message)?.as_bytes()).expect("Write js/HEX.sig.json file");
    println!("Write file successed: {}", js_sign_file);
    Ok(())
}