# prefix is inserted above by make

# go $1 days back in the news feed and adjust .nn/rc
# accordingly.

USE_HIST=false
if [ "$1" = "-h" ]
then
	USE_HIST=true
	shift
fi
 
if [ $# -ne 1 ]
then
	echo "Usage: $0 [-h] days"
	exit 1
fi

if [ $USE_HIST = false ]
then
	if [ -s $DB/active.$1 ]
	then
	  nntidy - $DB/active.$1
	else
	  echo $0: No suitable copy of the active file exists -- no update
	fi
	exit 0
fi

HISTORY="`expr $ACTIVE : '\(/.*/\)'`"history

if [ -s "${HISTORY}" ]
then
	:
elif [ -s "${HISTORY}.d/0" ]
then
	HISTORY="${HISTORY}.d/*"
else
	if $NNTP
	then
		echo "$0 is not setup to run with NNTP"
		exit 2
	fi
	echo "Cannot find the history file -- no update"
	exit 1
fi

echo Working on your nn record file ... do not run nn until completed

echo "NOTICE:  this operation is SLOOOOOOOOWWWWWWWW....."

cd
cd .nn
rm -f rc.bak1

trap "mv rc.bak1 rc ; echo No changes ; exit 0" 1 2 3 13 14 15

mv rc rc.bak1

{
echo PHASE_1
# news.group last.art.no first.art.no mod
cat $ACTIVE

echo PHASE_2
# + last.read.art.no news.group
cat rc.bak1

echo PHASE_3
# from date time news.group/art.no ...
cat  $HISTORY | egrep "`$LIB/date_regexp $1`"
} |
awk '
BEGIN{
	p=0
}
/^PHASE_/ {
	p++
	next
}
p == 1 {
	last[$1]=$2+1
	next
}
p == 2 {
	if (last[$3] > 0) {
		subscr[$3] = $1
		if ($1 == "!") last[$3] = $2 + 1;
	}
	next
}
p == 3 {
	for (i = 4; i <= NF; i++) {
		if (split($i, x, "/") != 2) continue;
		g=x[1]; n=x[2]
		if (subscr[g] == "+" && n < last[g]) last[g] = n
	}
}
END {
	for (g in subscr) printf("%s %06d %s\n", subscr[g], last[g]-1, g)
}' | sort +2 > rc

echo "nngoback $1 finished"
