Skip to main content

second_brain_core/
machine.rs

1use anyhow::{Context, Result};
2use serde::{Deserialize, Serialize};
3use std::path::Path;
4use uuid::Uuid;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7pub struct MachineIdentity {
8    pub id: String,
9    pub name: String,
10}
11
12impl MachineIdentity {
13    pub fn load_or_create(config_dir: &Path) -> Result<Self> {
14        let path = config_dir.join("machine.toml");
15        if path.exists() {
16            let content =
17                std::fs::read_to_string(&path).context("reading machine.toml")?;
18            let identity: MachineIdentity =
19                toml::from_str(&content).context("parsing machine.toml")?;
20            return Ok(identity);
21        }
22        let name = hostname::get()
23            .map(|h| h.to_string_lossy().to_string())
24            .unwrap_or_else(|_| "unknown".to_string());
25        let identity = MachineIdentity {
26            id: Uuid::new_v4().to_string(),
27            name,
28        };
29        std::fs::create_dir_all(config_dir)
30            .context("creating config directory")?;
31        std::fs::write(&path, toml::to_string_pretty(&identity)?)
32            .context("writing machine.toml")?;
33        Ok(identity)
34    }
35
36    pub fn config_dir() -> Result<std::path::PathBuf> {
37        let home = dirs::home_dir().context("cannot determine home directory")?;
38        Ok(home.join(".second-brain"))
39    }
40}