fn default_client_pki_dir() -> PathBuf {
    if let Some(home) = std::env::var_os("HOME") {
        return PathBuf::from(home).join(".config/lesavka/pki");
    }
    std::env::current_dir()
        .unwrap_or_else(|_| PathBuf::from("."))
        .join(".config/lesavka/pki")
}

fn install_client_pki_bundle(bundle: &Path) -> Result<PathBuf, String> {
    let target = default_client_pki_dir();
    let scratch = std::env::temp_dir().join(format!(
        "lesavka-client-pki-{}",
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_millis()
    ));
    std::fs::create_dir_all(&scratch)
        .map_err(|err| format!("could not create extraction folder: {err}"))?;
    let extract = Command::new("tar")
        .arg("-xzf")
        .arg(bundle)
        .arg("-C")
        .arg(&scratch)
        .status()
        .map_err(|err| format!("tar is unavailable: {err}"))?;
    if !extract.success() {
        let _ = std::fs::remove_dir_all(&scratch);
        return Err(format!("could not extract {}", bundle.display()));
    }
    for item in ["ca.crt", "client.crt", "client.key"] {
        if !scratch.join(item).is_file() {
            let _ = std::fs::remove_dir_all(&scratch);
            return Err(format!("bundle is missing {item}"));
        }
    }
    std::fs::create_dir_all(&target)
        .map_err(|err| format!("could not create {}: {err}", target.display()))?;
    for item in ["ca.crt", "client.crt", "client.key"] {
        std::fs::copy(scratch.join(item), target.join(item))
            .map_err(|err| format!("could not install {item}: {err}"))?;
    }
    tighten_client_key_permissions(&target.join("client.key"));
    let _ = std::fs::remove_dir_all(&scratch);
    Ok(target)
}

#[cfg(unix)]
fn tighten_client_key_permissions(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    if let Ok(mut permissions) = std::fs::metadata(path).map(|metadata| metadata.permissions()) {
        permissions.set_mode(0o600);
        let _ = std::fs::set_permissions(path, permissions);
    }
}

#[cfg(not(unix))]
fn tighten_client_key_permissions(_path: &Path) {}
