Skip to main content

lighthouse_manager/commands/
set_managed.rs

1use anyhow::{Result, bail};
2use tracing::info;
3
4use crate::storage;
5
6/// Represents either a single lighthouse index or a request to target all entries.
7enum IndexOrAll {
8    All,
9    Index(usize),
10}
11
12/// Parse the target argument: "all" for every lighthouse, or a numeric index.
13fn parse_target(target: &str, db_len: usize) -> Result<IndexOrAll> {
14    if target == "all" {
15        return Ok(IndexOrAll::All);
16    }
17
18    let idx: usize = target
19        .parse()
20        .map_err(|_| anyhow::anyhow!("Invalid index '{target}'. Use a number or 'all'."))?;
21
22    if idx >= db_len {
23        bail!(
24            "Index {idx} out of range (database has {db_len} entries). Use `lighthouse-manager list` to see available indices."
25        );
26    }
27
28    Ok(IndexOrAll::Index(idx))
29}
30
31/// Set the managed flag on one or all lighthouses.
32///
33/// # Errors
34///
35/// Returns an error if the database cannot be loaded, the target index is invalid,
36/// or the database cannot be saved.
37pub fn run(target: &str, managed: bool) -> Result<()> {
38    let mut db = storage::load()?;
39
40    if db.lighthouses.is_empty() {
41        bail!(
42            "No lighthouses in the database. Run `lighthouse-manager discover` to scan for nearby devices."
43        );
44    }
45
46    let label = if managed { "managed" } else { "unmanaged" };
47    let target = parse_target(target, db.lighthouses.len())?;
48
49    match target {
50        IndexOrAll::All => {
51            for lh in &mut db.lighthouses {
52                lh.managed = managed;
53            }
54            info!(
55                count = db.lighthouses.len(),
56                label,
57                "Set {} lighthouse(s) as {}",
58                db.lighthouses.len(),
59                label
60            );
61        }
62        IndexOrAll::Index(idx) => {
63            db.lighthouses[idx].managed = managed;
64            let name = db.lighthouses[idx].name.as_str();
65            info!(
66                index = idx,
67                name = %name,
68                "Set '{name}' at index [{idx}] as {label}"
69            );
70        }
71    }
72
73    storage::save(&db)?;
74
75    Ok(())
76}