#!/bin/sh
# Path where Dracut mounts the ISO

command -v getarg > /dev/null || . /lib/dracut-lib.sh

ISO_PATH="/run/initramfs/live/kdeos/x86_64"
LAYERS_ROOT="/run/kaos/layers"
LOWERDIR=""

# Find and mount all .sqfs files except the main root (already mounted at $NEWROOT)
# 'ls' ensures they are processed in alphabetical order (01, 02, 03...)
for sqfs in $(ls "$ISO_PATH"/*.sqfs 2>/dev/null); do
    FILENAME=$(basename "$sqfs")
    
    # Skip the base image handled by dmsquash-live
    [ "$FILENAME" = "root-image.sqfs" ] && continue
    
    MNT="$LAYERS_ROOT/${FILENAME%.sqfs}"
    mkdir -p "$MNT"
    mount -t squashfs -o loop,ro "$sqfs" "$MNT"
    
    # Build the lowerdir string: Newest layers come FIRST in the string
    if [ -z "$LOWERDIR" ]; then
        LOWERDIR="$MNT"
    else
        LOWERDIR="$MNT:$LOWERDIR"
    fi
done

# Add the existing $NEWROOT (the clean base) to the bottom of the stack
if [ -n "$LOWERDIR" ]; then
    UPPERDIR="$LAYERS_ROOT/upper"
    WORKDIR="$LAYERS_ROOT/work"
    mkdir -p "$UPPERDIR" "$WORKDIR"
    
    # tmpfs for the writable upper layer
    mount -t tmpfs tmpfs "$LAYERS_ROOT/rw" -o mode=755
    mkdir -p "$LAYERS_ROOT/rw/upper" "$LAYERS_ROOT/rw/work"
    
    info "KaOS-Layers: Stacking layers: $LOWERDIR"
    mount -t overlay overlay \
        -o lowerdir="$LOWERDIR:$NEWROOT",upperdir="$LAYERS_ROOT/rw/upper",workdir="$LAYERS_ROOT/rw/work" \
        "$NEWROOT"
fi
