#!/bin/sh
# Executed by Debian Installer after the user confirms the disk and creates their account.
set -eu
media=/cdrom/newworld
target=/target
test -s "$media/repo/Packages.gz"
test -s "$media/rootfs.tar.gz"
mkdir -p "$target/opt/newworld-install-media"
mount -o bind /cdrom "$target/opt/newworld-install-media"
trap 'umount "$target/opt/newworld-install-media" || true; rmdir "$target/opt/newworld-install-media" || true' EXIT
cat > "$target/etc/apt/newworld-install.list" <<'EOF'
deb [trusted=yes] file:/opt/newworld-install-media/newworld/repo ./
EOF
txn() {
    in-target env DEBIAN_FRONTEND=noninteractive apt-get \
        -o Dir::Etc::sourcelist=/etc/apt/newworld-install.list -o Dir::Etc::sourceparts=- \
        -o Acquire::Languages=none -o Acquire::Retries=0 -o APT::Get::List-Cleanup=false "$@"
}
txn update
# Package names originate in the pinned desktop manifest carried by the USB.
set -- $(cat "$media/packages.list")
# Install common Wi-Fi and graphics firmware directly from the authenticated
# Debian media pool, including for supported adapters attached after setup.
for name in $(cat "$media/firmware.list"); do
    found=false
    for blob in /cdrom/firmware/"${name}"_*.deb; do
        [ -f "$blob" ] || continue
        set -- "$@" "/opt/newworld-install-media/firmware/${blob##*/}"
        found=true
    done
    [ "$found" = true ] || { echo "Missing stock Debian firmware: $name" >&2; exit 1; }
done
txn -y --no-install-recommends install "$@"
tar -xzf "$media/rootfs.tar.gz" -C "$target"
for lang in en_US he_IL; do
    if ! grep -qx "${lang}.UTF-8 UTF-8" "$target/etc/locale.gen"; then
        printf '%s.UTF-8 UTF-8\n' "$lang" >> "$target/etc/locale.gen"
    fi
done
in-target locale-gen
test -x "$target/usr/bin/firefox-esr"
test -x "$target/usr/bin/startxfce4"
test -x "$target/usr/bin/guvcview"
test -x "$target/usr/bin/arecord"
test -x "$target/usr/sbin/wpa_supplicant"
test -x "$target/usr/sbin/cupsd"
test -x "$target/usr/bin/newworld-settings32"
test -x "$target/usr/local/lib/newworld/xfce-session"
test -x "$target/usr/local/lib/compact-desktop/consent/agreement_ui.py"
in-target update-alternatives --set x-session-manager /usr/bin/startxfce4
# Restore Debian's authenticated network repositories for future security upgrades.
cat > "$target/etc/apt/sources.list.d/newworld-debian.sources" <<'EOF'
Types: deb
URIs: https://deb.debian.org/debian
Suites: bookworm bookworm-updates
Components: main non-free-firmware
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg

Types: deb
URIs: https://deb.debian.org/debian-security
Suites: bookworm-security
Components: main
Signed-By: /usr/share/keyrings/debian-archive-keyring.gpg
EOF
# Installer media may be removed on reboot.
sed -i '/^[[:space:]]*deb cdrom:/s/^/# /' "$target/etc/apt/sources.list"
rm -f "$target/etc/apt/newworld-install.list"
in-target apt-get clean
