#!/bin/bash

# LibrePortal WebUI Atomic Write Utilities
# Provides atomic file writing functionality for web UI safety

# Atomic file write function for web UI safety
atomicWriteWebUI() {
    local content="$1"
    local target_file="$2"
    local temp_file="${target_file}.tmp.$$"

    # Ensure directory exists
    mkdir -p "$(dirname "$target_file")"

    # Write to temp file first
    printf '%s' "$content" > "$temp_file"

    # Set proper permissions
    chmod 644 "$temp_file"

    # Atomic rename (instantaneous - no partial reads)
    mv "$temp_file" "$target_file"

    if [ $? -eq 0 ]; then
        echo "✓ Atomic write successful: $target_file"
    else
        echo "✗ Atomic write failed: $target_file"
    fi
}
