#!/bin/sh

CHROOT=$(mount | grep proc | grep calamares | awk '{print $3}' | sed -e "s#/proc##g")
KNOWN_MEDIUM_PATHS="/run/live/medium /run/initramfs/live"
RELEASE="trixie"

# Support both dracut and initramfs configurations to avoid substitutions
# in live-build, see: #1089618
for path in $KNOWN_MEDIUM_PATHS; do
    if [ "$(mount | grep "$path" | cut -f3 -d" ")" = "$path" ]; then
        MEDIUM_PATH=$path
    fi
done

if [ "$1" = "-u" ]; then
    umount "$CHROOT/$MEDIUM_PATH"
    rm "$CHROOT/etc/apt/sources.list.d/debian-live-media.list"
    chroot "$CHROOT" apt-get update
    exit 0
fi

# Remove the base sources, we will configure sources in a later phase
rm -f "$CHROOT/etc/apt/sources.list.d/base.list"

mkdir -p "$CHROOT/$MEDIUM_PATH"
mount --bind "$MEDIUM_PATH" "$CHROOT/$MEDIUM_PATH"
echo "deb [trusted=yes] file:$MEDIUM_PATH $RELEASE main" > "$CHROOT/etc/apt/sources.list.d/debian-live-media.list"
chroot "$CHROOT" apt-get update
# Attempt safest way to remove cruft
rmdir "$CHROOT/run/live/medium"
rmdir "$CHROOT/run/live"

exit 0
