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

target_root="${1:-}"

if [ -z "$target_root" ] || [ "$target_root" = "/" ]; then
    echo "Invalid Calamares target root: ${target_root:-empty}" >&2
    exit 1
fi

installer="${TUXENIX_ROOTFS_INSTALLER:-/run/iso/tuxenix-install-rootfs.sh}"
archive="${TUXENIX_ROOTFS_IMAGE:-/run/iso/live/tuxenix-rootfs.tar.zst}"

if [ ! -f "$archive" ]; then
    echo "Tuxenix rootfs image is missing: $archive" >&2
    exit 1
fi

echo "Copying Tuxenix root filesystem image into $target_root"
echo "archive: $archive"
echo
echo "tools:"
command -v tar
command -v zstd
tar --version | head -1 || true
zstd --version || true
echo
echo "space:"
df -h "$target_root" "$(dirname "$archive")" /tmp 2>/dev/null || true
echo
ls -lh "$archive"
echo
echo "Testing compressed image..."
zstd -t "$archive"
echo "Extracting image..."
zstd -dc "$archive" | tar -xpf - -C "$target_root" --numeric-owner --delay-directory-restore
echo "Image copy complete."
