#!/bin/bash

# If $1 is an integer >= 0, assign it to <rounds>, otherwise default to 50
# Trick: use 0 to just print a report of previously existing logs again
[ "$1" -eq "$1" -a $1 -ge 0 ] > /dev/null 2>&1 \
	&& rounds=$1 \
	|| rounds=50

warn_dir=kconfig-warnings
conf_file=.config
warn_file=conf-warnings.log

# Create output directory and refresh config cache
mkdir -p $warn_dir
make config-cache > /dev/null

# Create <rounds> random configurations + warning logs and move them
# to separate subdirectories (keep existing ones!)
while ((r++ < rounds)); do

	# Capture stderr (=warnings) in buffer
	IFS=$'\n'
	warn_buf=($(tools/kconfig/conf --randconfig config/.cache.in 2>&1 > /dev/null))
	unset IFS

	# On error in 'conf --randconfig' skip this round
	[ $? -eq 0 ] || continue
	# If no warnings were detected skip this round
	[ ${#warn_buf[@]} -eq 0 ] && rm $conf_file && continue

	# Compare warnings found in this round with warnings collected so far.
	# Each previously unknown warning is added to the list of all warnings.
	tmp_dir_created=n
	for (( i=0; i<${#warn_buf[@]}; i++ )); do
		found=n
		for (( j=0; j<${#warn_all[@]}; j++ )); do
			if [ "${warn_buf[i]}" == "${warn_all[j]}" ]; then
				# Warning was already known -> no need to search further
				found=y
				break
			fi
		done
		# Skip the rest of this loop for previously known warnings
		[ "$found" == "y" ] && continue

		# Add new warning to collection
		warn_all[${#warn_all[@]}]=${warn_buf[i]}
		# Create <tmp_dir> for this round and move <conf_file> to it
		if [ "$tmp_dir_created" == "n" ]; then
			tmp_dir=$(mktemp -d --tmpdir=$warn_dir "XXXXXXXX")
			tmp_dir_created=y
			mv $conf_file $tmp_dir
		fi
		# Log new warning to console and corresponding <warn_file>
		echo "${warn_buf[i]}"
		echo "${warn_buf[i]}" >> $tmp_dir/$warn_file 
	done
done

# Dump unique warnings stored in <warn_dir> for <rounds>==0
[ $rounds -eq 0 ] && find $warn_dir -type f -name $warn_file | xargs cat | sort | uniq