# helpers.sh — Core logging, error handling, and validation helpers.
# shellcheck shell=bash
# Sourced by entrypoint.sh before any other module.
# Copyright (c) 2026 Progralink. Licensed under the DevCage License — see LICENSE.

# Session log path (set from env at source time so all functions inherit it).
_SESSION_LOG="${DEVCAGE_SESSION_LOG:-}"

_entrypoint_log() {
    if [ "$_SESSION_LOG" != "" ]; then
        printf '%s\n' "entrypoint: $*" >> "$_SESSION_LOG" 2>/dev/null || true
    fi
}

warn() { echo "entrypoint: WARNING: $*" >&2; _entrypoint_log "WARNING: $*"; }
die()  { echo "entrypoint: ERROR: $*" >&2; _entrypoint_log "ERROR: $*"; exit 1; }

# Strip Windows CRLF from a file in-place (no-op if already Unix).
# Used for host-mounted config/scripts that may have \r\n line endings.
_strip_crlf() { sed -i 's/\r$//' "$@" 2>/dev/null || true; }

# Validate package names; populate _validated_pkgs global array on success.
# Args: pkgs_string  regex  label
_validate_packages() {
    local pkgs="$1" regex="$2" label="$3"
    _validated_pkgs=()
    read -ra _pkg_list <<< "$pkgs"
    for pkg in "${_pkg_list[@]}"; do
        if ! [[ "$pkg" =~ $regex ]]; then
            die "invalid ${label} package name '${pkg}'"
        fi
        _validated_pkgs+=("$pkg")
    done
}
