#!/bin/sh
# Copyright © 2006-2018 Canonical Ltd.
# Copyright © 2022 Paul Gevers
# Copyright © 2022 Simon McVittie
# SPDX-License-Identifier: GPL-2.0-or-later

# This script writes the requested apt_source_line to the
# apt_source_filename and updates the apt index for just added entry
# (and only that one)

# Usage $0 <apt_source_line> <apt_source_filename>

set -eu

usage () {
    echo "Usage: $0 APT_SOURCE_LINE APT_SOURCE_FILENAME" >&2
    exit 2
}

if [ "$#" -lt 2 ]; then
    usage
fi

# Check for options for future-proofing, but none are actually accepted
case "${1-}" in
    (--)
        shift
        ;;

    (-*)
        usage
        ;;
esac

echo "$1" >> /etc/apt/sources.list.d/"$2"
# retry only needed before Debian 9 (buster) and Ubuntu 18.04 (bionic)
# testbed has 'Acquire::Retries "10";' apt config
for retry in 1 2 3; do
    apt-get --no-list-cleanup \
    -o Dir::Etc::sourcelist=/etc/apt/sources.list.d/"$2" \
    -o Dir::Etc::sourceparts=/dev/null \
    update 2>&1 && break
    if [ $retry = 3 ] ; then
        return 1
    else
        sleep 15
    fi
done
