#!/bin/bash -eux

# Configure apt so that installs from the pool on the cdrom are preferred
# during installation but not in the installed system.
#
# This has a few steps.
#
# 1. As the remaining steps mean that any changes to apt configuration are do
#    not persist into the installed system, we get curtin to configure apt a
#    bit earlier than it would by default.
#
# 2. Bind-mount the cdrom into the installed system as /run/cdrom
#
# 3. Set up an overlay over /target/etc/apt. This means that any changes we
#    make will not persist into the installed system and we do not have to
#    worry about cleaning up after ourselves.
#
# 4. Configure apt in /target to look at the pool on the cdrom.  This has two
#    subcases:
#
#     a. if we expect the network to be working, this basically means
#        prepending "deb file:///run/cdrom $(lsb_release -sc) main restricted"
#        to the sources.list file.
#
#     b. if the network is not expected to be working, we replace the
#        sources.list with a file just referencing the cdrom.
#
# 5. If the network is not expected to be working, we also set up an overlay
#    over /target/var/lib/apt/lists (if the network is working, we'll run "apt
#    update" after the /target/etc/apt overlay has been cleared).

if [ -z "$TARGET_MOUNT_POINT" ]; then
    # Nothing good can happen from running this script without
    # TARGET_MOUNT_POINT set.
    exit 1;
fi

PY=$1
HAS_NETWORK=$2

$PY -m curtin apt-config

setup_overlay () {
    local dir=$1
    local t=$(mktemp -d)
    mkdir $t/work $t/upper
    mount -t overlay overlay -o lowerdir=$dir,workdir=$t/work,upperdir=$t/upper $dir
}

setup_overlay $TARGET_MOUNT_POINT/etc/apt

mkdir -p "$TARGET_MOUNT_POINT/cdrom"
mount --bind /cdrom "$TARGET_MOUNT_POINT/cdrom"

if [ $HAS_NETWORK = 'true' ]; then
    mv "$TARGET_MOUNT_POINT/etc/apt/sources.list" "$TARGET_MOUNT_POINT/etc/apt/sources.list.d/original.list"
else
    # Do not use the configured proxy during the install if one was configured.
    rm -f $TARGET_MOUNT_POINT/etc/apt/apt.conf.d/90curtin-aptproxy
    setup_overlay $TARGET_MOUNT_POINT/var/lib/apt/lists
fi

cat > "$TARGET_MOUNT_POINT/etc/apt/sources.list" <<EOF
deb file:///cdrom $(lsb_release -sc) main restricted
EOF

$PY -m curtin in-target -- apt-get update
