#!/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

ensure_line() {
    file="$1"
    pattern="$2"
    line="$3"

    touch "$file"
    if ! grep -Eq "$pattern" "$file"; then
        printf '%s\n' "$line" >> "$file"
    fi
}

ensure_target_account() {
    mkdir -p "$target_root/etc" "$target_root/var/lib/dbus"
    ensure_line "$target_root/etc/group" '^messagebus:' \
        'messagebus:x:18:'
    ensure_line "$target_root/etc/passwd" '^messagebus:' \
        'messagebus:x:18:18:System Message Bus:/run/dbus:/bin/false'
    ln -snf /etc/machine-id "$target_root/var/lib/dbus/machine-id"
    chmod 755 "$target_root/var/lib/dbus"
}

ensure_login_target() {
    if [ ! -x "$target_root/usr/sbin/dinit" ]; then
        echo "Installed root is missing dinit." >&2
        exit 1
    fi

    rm -f "$target_root/usr/sbin/init"
    ln -snf dinit "$target_root/usr/sbin/init"
}

ensure_runtime_layout() {
    if [ -d "$target_root/usr/lib/modules" ] && [ ! -e "$target_root/lib/modules" ]; then
        mkdir -p "$target_root/lib"
        ln -snf ../usr/lib/modules "$target_root/lib/modules"
    fi

    mkdir -p "$target_root/etc/profile.d"
    cat > "$target_root/etc/profile.d/00-tuxenix-path.sh" <<'EOF'
# Make base admin tools available in text logins.
case ":$PATH:" in
    *:/usr/sbin:*) ;;
    *) PATH="/usr/sbin:$PATH" ;;
esac
case ":$PATH:" in
    *:/sbin:*) ;;
    *) PATH="/sbin:$PATH" ;;
esac
export PATH
EOF
    chmod 644 "$target_root/etc/profile.d/00-tuxenix-path.sh"

    cat > "$target_root/etc/resolv.conf" <<'EOF'
nameserver 1.1.1.1
nameserver 8.8.8.8
EOF
    chmod 644 "$target_root/etc/resolv.conf"
}

preserve_network_connections() {
    source_connections="${TUXENIX_LIVE_CONNECTIONS_DIR:-/etc/NetworkManager/system-connections}"
    target_connections="$target_root/etc/NetworkManager/system-connections"
    copied=0

    install -d -o root -g root -m 0700 "$target_connections"
    if [ ! -d "$source_connections" ]; then
        return
    fi

    for profile in "$source_connections"/*.nmconnection; do
        if [ ! -f "$profile" ]; then
            continue
        fi
        install -o root -g root -m 0600 \
            "$profile" "$target_connections/$(basename "$profile")"
        copied=$((copied + 1))
    done

    if [ "$copied" -gt 0 ]; then
        echo "Preserved $copied NetworkManager connection profile(s)."
    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
ensure_target_account
ensure_login_target
ensure_runtime_layout
preserve_network_connections
echo "Image copy complete."
