#!/bin/sh
#
# $Id: update.sh,v 1.8 2008/10/31 14:41:21 winter Exp $

bd=`pwd`
ls data/*.txt 2>&- > /dev/null
if [ $? -eq 1 ]; then
	page=0
else
	page=`cat data/*.txt 2>/dev/null | grep -e '^[[:digit:]]\+	25' | awk -F "\t" '{print $1}' | sort -n | uniq | tail -1`
	if [ -z ${page} ]; then
		page=0
	fi
fi

thread=`../scripts/thread-status.pl`
if [ $? -eq 1 ]; then
	echo ERROR: thread-status.pl returned $?.
	exit 1
fi

echo page $page thread $thread
next=`expr $page + 1`

if [ "$thread" -gt "$page" ]; then
	echo -n "Updating at "
	date

	last=`expr $thread + 1`

	if [ "$next" -eq "$thread" ]; then
		file="${next}.txt"
	else
		file="${next}-${thread}.txt"
	fi
	echo page $page
	echo thread $thread
	echo next $next
	echo last $last
	echo saving to $file

	../scripts/thread.pl $next $last > data/$file
	if [ $? -eq 1 ]; then
		echo ERROR: thread.pl returned $?.
		exit 1
	fi

	../scripts/regen.sh $thread
	../scripts/mkanim.sh
else
	if [ -e partial-updates ]; then
		file="${next}.txt"

		last=`expr $next + 1`

		echo page $page
		echo thread $thread
		echo next $next
		echo last $last
		echo saving to $file

		../scripts/thread.pl $next $last > data/$file
		if [ $? -eq 1 ]; then
			echo ERROR: thread.pl returned $?.
			exit 1
		fi

		../scripts/regen.sh $next

		echo -n "Partial update ($file) at "
		date
	else
		echo -n "No update needed at "
		date
	fi
fi
