#! /bin/sh
#
# convert the directory/file structure for http-analyze
#

STDIR=""
YEAR=""
MON=""

while [ -z "$STDIR" ]; do
	echo "Name of output directory for HTML files: \c"
	read answer
	case $answer in
	  '')	;;
	  *)	if [ ! -d $answer ]; then
			echo "$answer does not exist or is not a directory. Try again.\n" 1>&2
		else
			STDIR="$answer"
		fi ;;
	esac
done

echo "Name of private output directory for lists if any: \c"
read answer
case $answer in
  '')	;;
  *)	if [ ! -d $answer ]; then
		echo "$answer does not exist or is not a directory. Exiting.\n" 1>&2
		exit 1
	else
		PRVDIR="$answer"
	fi ;;
esac

[ -d "$STDIR" ] || { echo "$STDIR doesn't exist" 1>&2; exit 1; }

if [ ! -d "$STDIR/btn" ]; then
	echo "\nCreating files and buttons in '$STDIR'"
	mkdir $STDIR/btn
	cp files/3D* $STDIR; cp files/btn/* $STDIR/btn
	echo "Buttons installed in $STDIR." 1>&2
fi

cd $STDIR >/dev/null || { echo "Couldn't cd into $STDIR\n" 1>&2; exit 1; }

cur=0
for i in stats19??.html; do
	case $i in
	  'stats19??.html')
		exit 1
		;;
	  *)	year=`expr "X$i" : 'X[^1]*\(19..\)\.html'`
		PERIOD="${PERIOD:+$PERIOD }$year"
		[ "$year" -gt "$cur" ] && cur="$year"
		;;
	esac
done

echo "\nCreating subdirectories for $PERIOD"
for year in $PERIOD; do
	if [ ! -d "www${year}" ]; then
		echo "\tCreating 'www${year}'"
		mkdir www${year}
	else
		echo "'www${year}' already exist! Continue with the conversion? (y/n) [n] \c"
		read answer
		case $answer in
		  y|Y) ;;
		  *)   exit 1 ;;
		esac
	fi
	[ -n "$PRVDIR" ] &&  { \
		echo "\tCreating 'www${year}/$PRVDIR'"; \
		mkdir www${year}/$PRVDIR 2>/dev/null; }
done

: ${PRVDIR:="."}

echo "\nMoving HTML and GIF files into appropriate subdirectories:"
for year in $PERIOD; do
	sy=`expr "X$year" : 'X19\(..\)'`
	echo "\tstats${year}.html -> www${year}/index.html"
	mv stats${year}.html www${year}/index.html 2>/dev/null
	if TOTALS=`ls stats??${sy}.html 2>/dev/null`; then
		echo "\tstats??${sy}.html -> www${year}/"
		mv $TOTALS www${year} 2>/dev/null
		echo "$TOTALS" |
		  sed "s%stats\\(..${sy}.html\\)%ln www${year}/stats\\1 www${year}/totals\\1%g" | sh
	fi

	echo "\t[a-z]*[0-9][0-9]?${sy}.gif -> www${year}"
	mv [a-z]*[0-9][0-9]${sy}.gif www${year} 2>/dev/null
	echo "\t$PRVDIR/files??${sy}.html -> www${year}/$PRVDIR"
	mv $PRVDIR/files??${sy}.html www${year}/$PRVDIR 2>/dev/null
	echo "\t$PRVDIR/sites??${sy}.html -> www${year}/$PRVDIR"
	mv $PRVDIR/sites??${sy}.html www${year}/$PRVDIR 2>/dev/null
	cp gr-icon.gif www${year} 2>/dev/null
done

echo "\tindex.html,stats.html -> www${cur}"
mv index.html stats.html stats.gif gr-icon.gif www${cur} 2>/dev/null

echo "\tstats.hist -> www-stats.hist"
mv stats.hist www-stats.hist

echo "\nDone.\nYou should now run http-analyze to create an up-to-date summary."
echo "   -> Note that you will not see an index file in your stats directory"
echo "   -> unless you have run http-analyze for the current month."
echo "   -> The files for ${cur} will be created in '$STDIR/www${cur}'.\n"
exit 0
