use std::{env, fs::File};
use std::io::Write;

fn main()
{
    if std::env::var("DOCS_RS").is_ok() 
    {
        println!("cargo:warning=DOCS_RS, CApi scramrs_defs.h will not be build.");

        return;
    }

    let etc_path = "include/scramrs_defs.h";

    let mut curdir = std::env::current_dir().unwrap();
    curdir.push(etc_path);

    let mut hfile = 
        File::options()
            .create(true)
            .write(true)
            .truncate(true)
            .open(&curdir)
            .unwrap();

    let mut ft_std = false;
    let mut ft_nocapi = false;
    let mut ft_ring = false;
    let mut ft_excl_sha1 = false;
    
    for (name, _value) in env::vars() 
    {
        //println!("cargo:warning={}", name);
        if name.as_str() == "CARGO_FEATURE_STD"
        {
            ft_std = true;
        }
        else if name.as_str() == "CARGO_FEATURE_WITHOUT_CAPI"
        {
            ft_nocapi = true;
        }
        else if name.as_str() == "CARGO_FEATURE_USE_RING"
        {
            ft_ring = true;
        }
        else if name.as_str() == "CARGO_FEATURE_EXCLUDE_SHA!"
        {
            ft_excl_sha1 = true;
        }
    }

    writeln!(hfile, "// --- AUTOGENERATED ---").unwrap();
    writeln!(hfile, "#ifndef _SCRAMRS_DEFS").unwrap();
    writeln!(hfile, "#define _SCRAMRS_DEFS\n\n").unwrap();


    if ft_std == false
    {
        writeln!(hfile, "#define CAPI_SCRAM_NOSTD\n").unwrap();
    }
    else
    {
        writeln!(hfile, "// #define CAPI_SCRAM_NOSTD\n").unwrap();
    }

    if ft_nocapi == true
    {
        writeln!(hfile, "#define CAPI_SCRAM_NOCAPI").unwrap();
    }
    else
    {
        writeln!(hfile, "// #define CAPI_SCRAM_NOCAPI").unwrap();
    }

    if ft_ring == true
    {
        writeln!(hfile, "#define CAPI_SCRAM_USE_RING").unwrap();
    }
    else
    {
        writeln!(hfile, "// #define CAPI_SCRAM_USE_RING").unwrap();
    }

    if ft_excl_sha1 == true
    {
        writeln!(hfile, "#define CAPI_SCRAM_EXECLUDE_SHA1").unwrap();
    }
    else
    {
        writeln!(hfile, "// #define CAPI_SCRAM_EXECLUDE_SHA1").unwrap();
    }

    writeln!(hfile, "#endif").unwrap();

    hfile.flush().unwrap();

    drop(hfile);

    return;
}