#!/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.$$"

    # Every step runs as the path's owner so the manager-run runtime (Model A)
    # can write the dockerinstall-owned WebUI/app files. Temp + rename share the
    # target's directory, so the mv stays atomic (same filesystem, same owner).
    local op="runInstallOp" wop="runInstallWrite"
    if [[ "$target_file" == "$containers_dir"* || "$target_file" == "${LP_CONTAINERS_DIR:-/libreportal-containers}"/* ]]; then
        op="runFileOp"; wop="runFileWrite"
    fi

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

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

    # Set proper permissions
    $op chmod 644 "$temp_file"

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

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