#!/bin/sh
# conf_replace.sh -- Create modified ISO copy with replaced config files
# Parses HIPERISO_CONF_REPLACE="org=/path;new=/path" from environment
# If set, creates /tmp/modified.iso and prints its path on stdout.
# Called by init as a subprocess: _new=$(sh /conf_replace.sh)
# POSIX sh compatible

. /hiperiso-lib.sh

if [ -z "${HIPERISO_CONF_REPLACE:-}" ]; then
    # No conf_replace configured -- output nothing, exit clean
    return 0 2>/dev/null || exit 0
fi

_org=""
_new=""
OLDIFS="$IFS"
IFS=';'
for _pair in $HIPERISO_CONF_REPLACE; do
    case "$_pair" in
        org=*) _org="${_pair#org=}" ;;
        new=*) _new="${_pair#new=}" ;;
    esac
done
IFS="$OLDIFS"

if [ -z "$_org" ] || [ -z "$_new" ]; then
    hiperiso_log "conf_replace: malformed config, skipping"
    return 0 2>/dev/null || exit 0
fi

_new_abs="${DATA_MOUNT}${_new}"
if [ ! -f "$_new_abs" ]; then
    hiperiso_log "conf_replace: replacement file not found: $_new_abs"
    return 0 2>/dev/null || exit 0
fi

if ! command -v xorriso >/dev/null 2>&1; then
    hiperiso_log "conf_replace: xorriso not available, skipping ISO modification"
    return 0 2>/dev/null || exit 0
fi

_modified_iso="/tmp/modified.iso"
hiperiso_log "conf_replace: creating modified ISO copy"

if xorriso -indev "$ISO_PATH" \
    -outdev "$_modified_iso" \
    -boot_image any keep \
    -rm "$_org" \
    -add "$_new_abs"="$_org" \
    2>/dev/null; then

    if [ -f "$_modified_iso" ]; then
        hiperiso_log "conf_replace: modified ISO at $_modified_iso"
        # Output the path for the calling process to capture
        printf '%s' "$_modified_iso"
        return 0 2>/dev/null || exit 0
    fi
fi

hiperiso_log "conf_replace: xorriso failed, using original ISO"
rm -f "$_modified_iso" 2>/dev/null || true
return 0 2>/dev/null || exit 0
