#!/bin/sh
set -e

# Copyright © 2013-2017 Andreas Beckmann (anbe@debian.org)
# Copyright © 2018 Holger Levsen (holger@layer-acht.org)
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>


. /usr/share/piuparts/lib/read_config.sh

get_config_value MASTER global master-directory
get_config_value SECTIONS global sections
get_config_value TESTING global testing-suite

dryrun=""
logfiles=""
current=""
longterm=""

pass=""
fail="fail"
bugged=""
affected=""
untestable="untestable"

for arg in "$@"
do
	case "$arg" in
		--pass)
			shift
			pass="pass"
			;;
		--affected)
			shift
			affected="affected"
			;;
		--bugged)
			shift
			bugged="bugged"
			affected="affected"
			;;
		--current)
			shift
			current="yes"
			;;
		--longterm)
			shift
			longterm="yes"
			;;
		--dryrun)
			shift
			dryrun="yes"
			;;
		--logfiles)
			shift
			logfiles="yes"
			;;
		*)
			break
			;;
	esac
done

test -n "$1" || exit 1

TOTAL=0
recycle_logfiles()
{
	local log recycle
	for log in "$@"
	do
		recycle="$(dirname "$(dirname "$log")")/recycle"
		if [ -f "$log" ] && [ ! -f "$recycle/$(basename $log)" ]; then
			TOTAL=$(( $TOTAL + 1 ))
			if [ -n "$dryrun" ]; then
				echo "candidate: $log"
			else
				ln -fv "$log" $recycle/ || true
			fi
		fi
	done
}


if [ -n "$logfiles" ]; then
	recycle_logfiles "$@"
fi


if [ -z "$logfiles" ]; then

subdirs="$pass $fail $bugged $affected $untestable"
pattern=' ('"$1"')\.conf$'

#
# mark logs matching kpr tag $1 for recycling
#
OLDPWD=$(pwd)
LIST=$(mktemp)
for SECTION in $SECTIONS ; do
	test -d $MASTER/$SECTION || continue
	go=
	if [ -z "$current$longterm" ]; then
		go=yes
	else
		case "$SECTION" in
			# don't catch old*stable22testing
			*$TESTING*|testing*|*sid*|*experimental*)
				if [ "$current" = "yes" ]; then
					go=yes
				fi
				;;
			*22testing*)
				if [ "$longterm" = "yes" ]; then
					go=yes
				fi
				;;
		esac
	fi
	if [ "$go" != "yes" ]; then
		echo "Skip: $SECTION"
		continue
	fi
	cd $MASTER
	searchdirs=""
	for dir in $subdirs ; do
		searchdirs="$searchdirs $SECTION/$dir"
	done
	mkdir -p $searchdirs $SECTION/recycle

	grep -rlE "$pattern" --include '*.kpr' $searchdirs | sed 's/\.kpr$/.log/' > $LIST
	recycle_logfiles $(cat $LIST)
	cd "$OLDPWD"
done
rm -f $LIST

fi


if [ "$TOTAL" -gt "0" ]; then
	if [ -n "$dryrun" ]; then
		echo "Found $TOTAL candidate logfiles for recycling."
	else
		echo "Marked $TOTAL logfiles for recycling."
	fi
fi
