//! A folder of lab reports into the owner's object, sealed (`cotton_mac::health_import`).//!//! pnpm -s health:import <folder> --zone <IANA zone> [--dry] [--owner "<name>"]//! [--same "<printed name>=<person>"]… [--new "<printed name>"]… [--add-people] [--reread]//! [--base <url> --device-id <id> --token-file <path> [--key-file <path>] [--data-dir <dir>]]//!//! <folder> PDFs (each may have `<name>.json` beside it saying its mail_message_id) and//! `.eml` mails (each PDF attached is read, the mail's Message-ID kept); walked whole//! --zone the owner's zone, Asia/Kolkata: the times a report prints are read in it//! --dry read everything, write nothing; with --base and the device, the people and//! reports already held are read so the summary says what a run would do//! --owner which person is the owner (Apple Health is theirs; first in the switcher)//! --same a printed name is this person (a person's name or row id): answers an `asked`//! --new a printed name is a new person: answers a `proposed`//! --add-people every `proposed` person is made//! --reread write a report again though its PDF came in before (a better reader)//! --base … the object and this Mac as a vault device (`seal-device`), as music:import://! the rows and the PDF leave this Mac sealed//!//! stdout is the summary as JSON: per file counts, the test names not yet known and the//! line numbers that read as nothing; per person how many reports. Never a value, a range,//! an order id or a date. Exit 0 when every file was read; 1 when one did not read or waits.use std::process::ExitCode;use cotton_client::seal::DataKeyStoreas _;use cotton_mac::device::DeviceArgs;use cotton_mac::health_import::{files_in, run, FileIn, Keyed, Options, Plain, Summary};use cotton_mac::music::import::Memory;const USAGE: &str = "pnpm -s health:import <folder> --zone <IANA zone> [--dry] [--owner \"<name>\"] [--same \"<printed>=<person>\"] [--new \"<printed>\"] [--add-people] [--reread] [--base <url> --device-id <id> --token-file <path> [--key-file <path>] [--data-dir <dir>]]";fn main() -> ExitCode {let argv: Vec<String> = std::env::args().skip(1).collect();match go(&argv) {Ok(code) => code,Err(why) => { eprintln!("health-import: {why}\nusage: {USAGE}");ExitCode::from(2) } }}fn go(argv: &[String]) -> Result<ExitCode, String> {letmut folder = None;letmut zone = None;letmut device = DeviceArgs::default();letmut options = Options { zone: chrono_tz::Tz::UTC, dry: false, owner: None, same: Vec::new(), new_people: Vec::new(), add_people: false, reread: false };letmut at = 0;while at < argv.len() {let flag = argv[at].as_str();match flag {"--dry" | "--dry-run" => options.dry = true,"--add-people" => options.add_people = true,"--reread" => options.reread = true, _ if flag.starts_with("--") => {let value = argv.get(at + 1).ok_or_else(|| format!("{flag} needs a value"))?.clone(); at += 1;match flag {"--zone" => zone = Some(value.parse::<chrono_tz::Tz>().map_err(|_| format!("--zone {value} is not an IANA zone"))?),"--owner" => options.owner = Some(value),"--new" => options.new_people.push(value),"--same" => {let (printed, person) = value.split_once('=').ok_or("--same is \"<printed name>=<person>\"")?; options.same.push((printed.trim().to_string(), person.trim().to_string())); } _ if device.take(flag, &value) => {} _ => returnErr(format!("{flag} is not an option")), } } _ if folder.is_none() => folder = Some(std::path::PathBuf::from(cotton_mac_init_cwd(flag))), _ => returnErr(format!("{flag}: one folder only")), } at += 1; }let folder = folder.ok_or("name the folder of reports")?; options.zone = zone.ok_or("--zone is needed (the owner's, e.g. Asia/Kolkata)")?;let files = files_in(&folder)?;if files.is_empty() {returnErr(format!("{} holds no PDF and no .eml", folder.display())); }let summary = if device.base.is_some() { on_the_object(&device, files, &options)? } elseif options.dry { run(&Memory::new("dry-run"), &Plain, files, &options).map_err(|e| e.to_string())? } else {returnErr("a run that writes needs --base, --device-id and --token-file (or say --dry)".into()); }; println!("{}", serde_json::to_string_pretty(&summary).expect("the summary serialises"));let whole = summary.files.iter().all(|file| matches!(file.outcome.as_str(), "added" | "updated" | "seen" | "older"));Ok(if whole { ExitCode::SUCCESS } else { ExitCode::from(1) })}/// A relative path is read from where pnpm was asked (INIT_CWD).fn cotton_mac_init_cwd(path: &str) -> String {match std::env::var("INIT_CWD") {Ok(base) if !std::path::Path::new(path).is_absolute() => std::path::Path::new(&base).join(path).display().to_string(), _ => path.to_string(), }}/// A run that writes, through this Mac opened as a vault device: the rows are/// keyed and sealed under the database's data key, which stays in here.fn on_the_object(device: &DeviceArgs, files: Vec<FileIn>, options: &Options) -> Result<Summary, String> {let opened = device.open()?;let dk = opened.keys.data_key(&opened.database_id)?.ok_or("the data key is not held")?;let keyer = Keyed { dk, database_id: opened.database_id.clone() }; run(&opened.object, &keyer, files, options).map_err(|e| e.to_string())}