1use std::collections::BTreeMap;
2use std::io::Write;
3use std::path::PathBuf;
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::AppError;
8
9pub const DEFAULT_CLIENT_ID: &str = "66ebad71-1604-48fc-a086-0d4caa24988b";
11pub const DEFAULT_TENANT: &str = "organizations";
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct Profile {
15 pub client_id: String,
16 #[serde(default = "default_tenant")]
17 pub tenant: String,
18 #[serde(default)]
19 pub read_only: bool,
20}
21
22impl Profile {
23 pub fn require_writable(&self) -> Result<(), AppError> {
24 if self.read_only {
25 Err(AppError::ReadOnly(
26 "read-only mode is enabled (unset TEAMS_READ_ONLY or disable read_only in the active profile to allow writes)"
27 .into(),
28 ))
29 } else {
30 Ok(())
31 }
32 }
33}
34
35fn default_tenant() -> String {
36 DEFAULT_TENANT.into()
37}
38
39#[derive(Debug, Default, Serialize, Deserialize)]
40struct ConfigFile {
41 #[serde(default)]
42 active_profile: Option<String>,
43 #[serde(default)]
44 profiles: BTreeMap<String, Profile>,
45}
46
47pub fn path() -> PathBuf {
48 if let Some(base) = std::env::var_os("XDG_CONFIG_HOME").filter(|v| !v.is_empty()) {
49 PathBuf::from(base).join("teams").join("config.toml")
50 } else {
51 config_base().join("teams").join("config.toml")
52 }
53}
54
55pub fn exists() -> bool {
56 path().is_file()
57}
58
59pub fn save(profile_name: &str, profile: Profile) -> Result<PathBuf, AppError> {
60 let path = path();
61 let mut config = read_file()?;
62 config.profiles.insert(profile_name.to_string(), profile);
63 config.active_profile = Some(profile_name.to_string());
64 let parent = path
65 .parent()
66 .ok_or_else(|| AppError::Unexpected("configuration path has no parent".into()))?;
67 std::fs::create_dir_all(parent)?;
68 let body = toml::to_string_pretty(&config).map_err(|e| AppError::Unexpected(e.to_string()))?;
69 let mut temp = tempfile::Builder::new()
70 .prefix(".config-")
71 .suffix(".toml.tmp")
72 .tempfile_in(parent)?;
73 temp.write_all(body.as_bytes())?;
74 temp.flush()?;
75 #[cfg(unix)]
76 {
77 use std::os::unix::fs::PermissionsExt;
78 std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o600))?;
79 }
80 temp.persist(&path).map_err(|error| error.error)?;
81 Ok(path)
82}
83
84pub fn load(requested: Option<&str>) -> Result<(String, Profile), AppError> {
85 let config = read_file()?;
86 let name = requested
87 .map(str::to_owned)
88 .or_else(|| std::env::var("TEAMS_PROFILE").ok())
89 .or(config.active_profile)
90 .unwrap_or_else(|| "default".into());
91 let stored = config.profiles.get(&name);
92 let client_id = std::env::var("TEAMS_CLIENT_ID")
93 .ok()
94 .or_else(|| stored.map(|profile| profile.client_id.clone()))
95 .ok_or_else(|| {
96 AppError::InvalidInput(format!(
97 "profile '{name}' is not configured; run `teams init` or set TEAMS_CLIENT_ID"
98 ))
99 })?;
100 let tenant = std::env::var("TEAMS_TENANT")
101 .ok()
102 .or_else(|| stored.map(|profile| profile.tenant.clone()))
103 .unwrap_or_else(default_tenant);
104 let read_only = match std::env::var("TEAMS_READ_ONLY") {
105 Ok(value) => parse_bool("TEAMS_READ_ONLY", &value)?,
106 Err(std::env::VarError::NotPresent) => stored.is_some_and(|profile| profile.read_only),
107 Err(error) => {
108 return Err(AppError::InvalidInput(format!(
109 "cannot read TEAMS_READ_ONLY: {error}"
110 )));
111 }
112 };
113 let profile = Profile {
114 client_id,
115 tenant,
116 read_only,
117 };
118 Ok((name, profile))
119}
120
121fn parse_bool(name: &str, value: &str) -> Result<bool, AppError> {
122 match value.trim().to_ascii_lowercase().as_str() {
123 "1" | "true" | "yes" | "on" => Ok(true),
124 "0" | "false" | "no" | "off" => Ok(false),
125 _ => Err(AppError::InvalidInput(format!(
126 "{name} must be true or false"
127 ))),
128 }
129}
130
131#[cfg(windows)]
132fn config_base() -> PathBuf {
133 dirs::config_dir().unwrap_or_else(|| PathBuf::from(".config"))
134}
135
136#[cfg(not(windows))]
137fn config_base() -> PathBuf {
138 dirs::home_dir()
139 .map(|home| home.join(".config"))
140 .unwrap_or_else(|| PathBuf::from(".config"))
141}
142
143pub fn configured_profile(requested: Option<&str>) -> Option<(String, Profile)> {
144 load(requested).ok()
145}
146
147fn read_file() -> Result<ConfigFile, AppError> {
148 match std::fs::read_to_string(path()) {
149 Ok(body) => toml::from_str(&body)
150 .map_err(|e| AppError::InvalidInput(format!("cannot parse {}: {e}", path().display()))),
151 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(ConfigFile::default()),
152 Err(e) => Err(e.into()),
153 }
154}