#!/usr/bin/env bash
set -euo pipefail

# ============================================================
# base_rootfs.bash
#
# 说明：
#   存放公共工具函数。
#   不保存 rootfs 运行状态。
#   rootfs 运行状态必须写入 function_rootfs.bash 中的 CTX 关联数组。
# ============================================================

log() {
  echo "[INFO] $*"
}

warn() {
  echo "[WARN] $*" >&2
}

err() {
  echo "[ERROR] $*" >&2
}

die() {
  err "$*"
  exit 1
}

assert_assoc_name() {
  local name="$1"

  if [[ ! "$name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
    die "invalid associative array name: $name"
  fi
}

assert_var_name() {
  local name="$1"

  if [[ ! "$name" =~ ^[a-zA-Z_][a-zA-Z0-9_]*$ ]]; then
    die "invalid variable name: $name"
  fi
}

require_cmd() {
  local cmd="$1"

  if ! command -v "$cmd" >/dev/null 2>&1; then
    die "missing command: $cmd"
  fi
}

copy_path_if_exists() {
  local src_root="$1"
  local dst_root="$2"
  local rel_path="$3"

  local src="$src_root/$rel_path"
  local dst="$dst_root/$rel_path"

  if [[ -d "$src" ]]; then
    log "copy dir: /$rel_path"
    sudo mkdir -p "$dst"
    sudo cp -a "$src/." "$dst/"
  elif [[ -e "$src" || -L "$src" ]]; then
    log "copy file: /$rel_path"
    sudo mkdir -p "$(dirname "$dst")"
    sudo cp -a "$src" "$dst"
  fi
}
