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

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

# unpackfs copies the live-build network mirror into the target as
# /etc/apt/sources.list. APT parses sources.list before sources.list.d/*, so
# when both offer the same version it picks the network copy and never falls
# back to the medium if that fetch fails -- which breaks every offline install
# at bootloader-config. Drop it here so the medium is the only source for the
# install phase; sources-final removes this file anyway.
rm -f $CHROOT/etc/apt/sources.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/blankon-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
