#!/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="echo"

# 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/parrot-live-media.list
    mv $CHROOT/etc/apt/parrot.list.disabled $CHROOT/etc/apt/sources.list.d/parrot.list || true
    mv $CHROOT/etc/apt/parrot.sources.disabled $CHROOT/etc/apt/sources.list.d/parrot.sources || true
    mv $CHROOT/etc/apt/sources.list.installer $CHROOT/etc/apt/sources.list
    rmdir $CHROOT/run/live/medium
    rmdir $CHROOT/run/live
    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/parrot-live-media.list
mv $CHROOT/etc/apt/sources.list.d/parrot.list $CHROOT/etc/apt/parrot.list.disabled || true
mv $CHROOT/etc/apt/sources.list.d/parrot.sources $CHROOT/etc/apt/parrot.sources.disabled || true
mv $CHROOT/etc/apt/sources.list $CHROOT/etc/apt/sources.list.installer
chroot $CHROOT apt update || true

exit 0
