#!/usr/bin/env bash if [[ -n "${ATLAS_FILES_SH_LOADED:-}" ]]; then return 0 fi ATLAS_FILES_SH_LOADED=1 atlas_ensure_directory() { local path="$1" local mode="${2:-0750}" local owner="${3:-}" if [[ -d "$path" ]]; then atlas_log_verbose "Directory already exists: ${path}" return 0 fi if [[ "${ATLAS_DRY_RUN:-0}" == "1" ]]; then atlas_log_info "Dry-run mode: would create directory ${path} with mode ${mode}" return 0 fi if [[ -n "$owner" ]]; then atlas_sudo_run install -d -m "$mode" -o "${owner%%:*}" -g "${owner##*:}" "$path" else atlas_sudo_run install -d -m "$mode" "$path" fi } atlas_backup_file() { local path="$1" local backup_dir="${2:-$(dirname "$path")}" local timestamp timestamp="$(date -u '+%Y%m%dT%H%M%SZ')" if [[ ! -e "$path" ]]; then return 0 fi local backup_path="${backup_dir}/$(basename "$path").${timestamp}.bak" if [[ "${ATLAS_DRY_RUN:-0}" == "1" ]]; then atlas_log_info "Dry-run mode: would back up ${path} to ${backup_path}" printf '%s\n' "$backup_path" return 0 fi if [[ ! -d "$backup_dir" ]]; then if [[ -w "$(dirname "$backup_dir")" ]]; then install -d -m 0750 "$backup_dir" else atlas_sudo_run install -d -m 0750 "$backup_dir" fi fi if [[ -w "$backup_dir" && -r "$path" ]]; then cp -a "$path" "$backup_path" else atlas_sudo_run cp -a "$path" "$backup_path" fi atlas_log_info "Backed up ${path} to ${backup_path}" printf '%s\n' "$backup_path" } atlas_replace_file_if_changed() { local source="$1" local destination="$2" local mode="${3:-0644}" local owner="${4:-}" local backup_dir="${5:-$(dirname "$destination")}" if [[ ! -f "$source" ]]; then atlas_log_error "Replacement source is not a file: ${source}" return "${ATLAS_EXIT_USAGE:-2}" fi if [[ -f "$destination" ]] && cmp -s "$source" "$destination"; then atlas_log_ok "No change required for ${destination}" return 0 fi if [[ "${ATLAS_DRY_RUN:-0}" == "1" ]]; then if [[ -e "$destination" ]]; then atlas_log_info "Dry-run mode: would back up and replace ${destination}" else atlas_log_info "Dry-run mode: would create ${destination}" fi return 0 fi if [[ -e "$destination" ]]; then atlas_backup_file "$destination" "$backup_dir" >/dev/null fi local destination_dir tmp_path destination_dir="$(dirname "$destination")" if [[ -w "$destination_dir" ]]; then tmp_path="$(mktemp "${destination}.tmp.XXXXXX")" else tmp_path="$(mktemp)" fi cp "$source" "$tmp_path" chmod "$mode" "$tmp_path" if [[ -n "$owner" ]]; then if [[ "${EUID}" -eq 0 ]]; then chown "$owner" "$tmp_path" elif [[ -w "$destination_dir" ]]; then chown "$owner" "$tmp_path" else sudo -n chown "$owner" "$tmp_path" fi fi if [[ -w "$destination_dir" ]]; then mv "$tmp_path" "$destination" else atlas_sudo_run install -m "$mode" "$tmp_path" "$destination" rm -f "$tmp_path" fi atlas_log_ok "Updated ${destination}" }