//! Small helpers for writing files with restrictive (owner-only) permissions.
//!
//! On Unix these create/restrict files to `0o600` so secret-bearing artifacts
//! (the vault, its snapshots, the audit log) are never readable by other local
//! users — even transiently during an atomic write-then-rename. On non-Unix
//! platforms the mode bits are not meaningful, so these degrade to a plain
//! write / no-op (Windows ACLs inherit from the parent directory's DACL, which
//! is the platform-appropriate boundary).

use std::path::Path;

use crate::errors::SafeResult;

/// Write `contents` to `path`, creating (and truncating) the file with
/// owner-only `0o600` permissions on Unix.
pub fn write_owner_only(path: &Path, contents: &[u8]) -> SafeResult<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut file = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)?;
        file.write_all(contents)?;
        file.flush()?;
    }
    #[cfg(not(unix))]
    {
        std::fs::write(path, contents)?;
    }
    Ok(())
}

/// Tighten an existing file to owner-only `0o600` on Unix. No-op elsewhere.
///
/// Used after an atomic rename to ensure a pre-existing destination file that
/// may have had looser permissions is brought down to owner-only.
pub fn set_owner_only(path: &Path) -> SafeResult<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))?;
    }
    #[cfg(not(unix))]
    {
        let _ = path;
    }
    Ok(())
}
