use std::fs;
mod common;
use common::Environment;

#[test]
fn create_environment() -> anyhow::Result<()> {
    let e = Environment::new()?;
    assert!(e.gnupg_state().exists());
    assert!(e.git_state().exists());
    Ok(())
}

#[test]
fn make_commit() -> anyhow::Result<()> {
    let e = Environment::new()?;
    let p = e.git_state();
    fs::write(p.join("a"), "Aller Anfang ist schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "Initial commit.",
    ])?;
    Ok(())
}

#[test]
fn sign_commit() -> anyhow::Result<()> {
    let e = Environment::new()?;
    let p = e.git_state();
    fs::write(p.join("a"), "Aller Anfang ist schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "Initial commit.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;
    Ok(())
}

#[test]
fn verify_commit() -> anyhow::Result<()> {
    let e = Environment::new()?;
    let p = e.git_state();
    e.sq_git(&[
        "policy",
        "authorize",
        e.willow.petname,
        &e.willow.fingerprint.to_string(),
        "--sign-commit"
    ])?;
    e.git(&["add", "openpgp-policy.toml"])?;
    e.git(&[
        "commit",
        "-m", "Initial commit.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;
    let root = e.git_current_commit()?;

    fs::write(p.join("a"), "Aller Anfang ist schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "First change.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;

    e.sq_git(&["log", "--trust-root", &root])?;

    fs::write(p.join("a"), "Und es bleibt schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "Second change.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;

    e.sq_git(&["log", "--trust-root", &root])?;

    Ok(())
}

#[test]
fn shadow_verify_commit() -> anyhow::Result<()> {
    let e = Environment::new()?;
    let p = e.git_state();

    e.sq_git(&[
        "policy",
        "authorize",
        "--policy-file", "shadow-policy.toml",
        e.willow.petname,
        &e.willow.fingerprint.to_string(),
        "--sign-commit"
    ])?;

    fs::write(p.join("a"), "Aller Anfang ist schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "Initial commit.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;
    let root = e.git_current_commit()?;

    e.sq_git(&[
        "log",
        "--trust-root", &root,
        "--policy-file", "shadow-policy.toml",
    ])?;

    fs::write(p.join("a"), "Und es bleibt schwer.")?;
    e.git(&["add", "a"])?;
    e.git(&[
        "commit",
        "-m", "Second change.",
        &format!("-S{}", e.willow.fingerprint),
    ])?;

    e.sq_git(&[
        "log",
        "--trust-root", &root,
        "--policy-file", "shadow-policy.toml",
    ])?;

    Ok(())
}
