#!/usr/bin/env runrs
//! ```cargo
//! [dependencies]
//! rust_util = { version = "0.6" }
//! ```

use std::fs;

use rust_util::{failure_and_exit, opt_result, util_cmd, XResult};

fn main() -> XResult<()> {
    let readme_template_file = "README_template.md";
    let readme_template = opt_result!(fs::read_to_string(readme_template_file),
        "Read {} failed: {}", readme_template_file);

    let output = util_cmd::run_command_or_exit("tree", &["-L", "2"]);
    if !output.status.success() {
        failure_and_exit!("Run tree -L 2 failed: {}", output.status);
    }
    let tree_output = String::from_utf8_lossy(&output.stdout).to_string();
    let tree_output_lines = tree_output.lines();
    let mut tree_lines = vec![];
    let ignored_file_list = vec![
        "LICENSE", "README.md", "README_template.md", "build_readme.js",
    ];
    for ln in tree_output_lines {
        let ignored = ignored_file_list.iter().any(|f| ln.ends_with(f));
        if !ignored {
            tree_lines.push(ln);
        }
    }
    let joined_tree_lines = tree_lines.join("\n");

    let readme = readme_template.replace("$$TREE_L2$$", &joined_tree_lines);
    opt_result!(fs::write("README.md", readme), "Write README.md failed: {}");
    Ok(())
}

// @SCRIPT-SIGNATURE-V1: yk-r1.ES256.20250308T212308+08:00.MEQCIBblLBxZYIuyjfsrCbQo
// oGiiiUGtdmjOo0p1s9DfPewYAiBZfpz6Nj737qGfejAPmnO03+NGuR0wc51NqXcer2WxKA==
