#!/bin/sh
# Check that the Debian/Ubuntu codenames used by the debchangelog,
# debsources and deb822sources syntax files
# (syntax/shared/debversions.vim) are read from distro-info, and that
# the hard-coded list is used when distro-info is not available.
# LP: #2161203
set -eu

WORKDIR=$(mktemp -d)
trap 'rm -rf "$WORKDIR"' EXIT
cd "$WORKDIR"

VIM=$(command -v vim)

fail() {
    echo "FAIL: $*"
    exit 1
}

# Write g:debSharedSupportedVersions and
# g:debSharedUnsupportedVersions, one codename per line, into the
# files "supported" and "unsupported"
dump_versions() {
    rm -f supported unsupported
    env PATH="${1:-$PATH}" "$VIM" -N -u NONE -i NONE -es \
        -c 'runtime syntax/shared/debversions.vim' \
        -c "call writefile(g:debSharedSupportedVersions, 'supported')" \
        -c "call writefile(g:debSharedUnsupportedVersions, 'unsupported')" \
        -c 'qa!' || true
    [ -s supported ] || fail "g:debSharedSupportedVersions is empty"
    [ -s unsupported ] || fail "g:debSharedUnsupportedVersions is empty"
}

echo "Test 1: codenames are read from distro-info"
dump_versions
for codename in $(debian-distro-info --supported) $(ubuntu-distro-info --supported); do
    grep -qx "$codename" supported || fail "supported codename '$codename' missing"
done
for codename in $(debian-distro-info --unsupported) $(ubuntu-distro-info --unsupported); do
    grep -qx "$codename" unsupported || fail "unsupported codename '$codename' missing"
done
for alias in oldstable stable testing unstable experimental devel; do
    grep -qx "$alias" supported || fail "alias '$alias' missing"
done

if grep -vqxE '[a-z][a-z0-9-]*' supported unsupported; then
    fail "unexpected entries: $(grep -vxhE '[a-z][a-z0-9-]*' supported unsupported)"
fi
echo "OK"

echo "Test 2: hard-coded fallback without distro-info"
mkdir empty
dump_versions "$WORKDIR/empty"
for codename in noble resolute sid devel; do
    grep -qx "$codename" supported || fail "fallback codename '$codename' missing"
done
grep -qx plucky unsupported || fail "fallback codename 'plucky' missing"
echo "OK"

echo "Test 3: development release is highlighted in debian/changelog"
devel=$(ubuntu-distro-info --devel 2>/dev/null || ubuntu-distro-info --latest)
cat > changelog <<EOF
hello (1.0-1) $devel; urgency=medium

  * Test.

 -- Test User <test@example.com>  Tue, 13 Oct 2026 12:00:00 +0000
EOF

# the codename starts at column 15
vim -N -u NONE -i NONE -es \
    -c 'syntax on' -c 'set filetype=debchangelog' \
    -c 'call writefile([synIDattr(synID(1, 15, 1), "name")], "synname")' \
    -c 'qa!' changelog || true
synname=$(cat synname)
[ "$synname" = debchangelogTarget ] || \
    fail "'$devel' highlighted as '$synname', expected 'debchangelogTarget'"
echo "OK"
