#!/bin/bash

set -eu

ONLINE_DOC=/docs/general-use/kali-linux-sources-list-repositories/

assert_notice() {
	kali-check-apt-sources 2>&1 >/dev/null | grep -q -F "$ONLINE_DOC" && return 0 || exit 1
}

assert_no_notice() {
	kali-check-apt-sources 2>&1 >/dev/null | grep -q -F "$ONLINE_DOC" || return 0 && exit 1
}

cd /etc/apt/

mkdir $AUTOPKGTEST_TMP/orig
[ -e sources.list   ] && mv sources.list   $AUTOPKGTEST_TMP/orig/
[ -e sources.list.d ] && mv sources.list.d $AUTOPKGTEST_TMP/orig/

cleanup() {
	cd /etc/apt/
	rm -fr sources.list sources.list.d/ sources.avail.d/

	cd $AUTOPKGTEST_TMP/orig/
	[ -e sources.list ]   && mv sources.list   /etc/apt/
	[ -e sources.list.d ] && mv sources.list.d /etc/apt/

	cd /
	rmdir $AUTOPKGTEST_TMP/orig
}

trap cleanup EXIT

#### Test with a variety of empty sources #################

# no sources
assert_notice

# empty sources.list
touch sources.list
assert_notice

# still empty sources.list
cat << EOF > sources.list
# this is a comment
  # another comment
# below, spaces or tabs:

  
	
EOF
assert_notice

# empty sources.list.d
mkdir sources.list.d
assert_notice

# empty files in sources.list.d
echo '# one-line-style format' > sources.list.d/foo.list
echo '# deb822-style format'   > sources.list.d/bar.sources
assert_notice

# non-empty file, but wrong name
echo 'deb fo bar' > sources.list.d/foo.conf
assert_notice
rm sources.list.d/foo.conf

#### Test sources that are not empty ######################

echo 'deb uri suite comp1 comp2' > sources.list.d/foo.list
assert_no_notice

echo 'Types: deb' > sources.list.d/bar.sources
assert_no_notice

echo 'deb kali.org kali main' > sources.list
assert_no_notice

rm -fr sources.list.d
assert_no_notice

#### Test some edge cases #################################

# the only source is a symlink
rm -fr sources.list sources.list.d
mkdir sources.avail.d sources.list.d
echo 'deb uri suite comp1 comp2' > sources.avail.d/foo.list
ln -s ../sources.avail.d/foo.list sources.list.d/foo.list
assert_no_notice
rm -fr sources.avail.d sources.list.d
