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

# This script returns the first suite found in apt sources. We can't just rely
# on /etc/os-release because it doesn't allow to distinguish between Debian
# unstable and testing.
#
# This release detection logic should be kept in sync with similar code in the
# setup-testbed script.
#
# For more information on APT data sources see sources.list(5).

# Usage $0

set -eu

distro=UNKNOWN
if [ -r /etc/os-release ]; then
    # shellcheck disable=SC1091
    distro=$(. /etc/os-release && echo "${ID:-$distro}")
fi

# Try guessing the default release from deb822-style format sources.
#
# While not mandatory, APT upstream expects distros to follow the
# <distro>.sources naming pattern for the default deb822 sources.
apt_sources="/etc/apt/sources.list.d/$distro.sources"
if [ -r "$apt_sources" ]; then
    release=$(sed -En 's/^Suites:\s*(\w+).*/\1/Ip' "$apt_sources" | head -n1)
    [ -n "$release" ] && echo "$release" && exit
fi

# Try guessing the default release from one-line-style format sources.
apt_sources=/etc/apt/sources.list
if [ -r "$apt_sources" ]; then
    release=$(sed -En '/^(deb|deb-src) +(\[.*\] *)?(http|https|file):/ { s/\[.*\] +//; s/^[^ ]+ +[^ ]* +([^ ]+) +.*$/\1/p }' "$apt_sources" | head -n1)
    [ -n "$release" ] && echo "$release" && exit
fi

# Could not guess the default release
echo "Could not guess the default release from the APT sources." >&2
exit 1
