#! /bin/sh
##########################################################################
# Shellscript:	newsstat - create news statistics
# Author     :	Heiner Steven <heiner.steven@odn.de>
# Date       :	1995-10-10
# Category   :	News
# SCCS-Id.   :	@(#) newsstat	1.1 02/02/26
##########################################################################
# Description
#     This program is usually run using "cron".
#     Needs the following non-standard programs:
#	newstop, newssub, inews, fdate
#
#     Cron does not execute $HOME/.profile, but scripts need
#     some variables there (i.e. the extended PATH)
##########################################################################

PN=`basename "$0"`			# Program name
VER='1.1'

PATH=/usr/local/lib/news:$PATH:$HOME/locbin:$HOME/cmds:/usr/local/bin
export PATH
: ${USER:=heiner}
: ${PUSER:=heiner.steven@odn.de}
: ${NNTPSERVER:=news.nefonline.de}
PN=`basename $0`

: ${MAIL:=mailx}			# "mail" command with "-s" option

ArchiveBase=$HOME/.newsstat
Date=`date '+%Y-%m-%d'`
NextWeek=`fdate 1 week`			# next week
Organization="Heiner's SHELLdorado: http://www.oase-shareware.org/shell/"

Usage () {
    echo >&2 "$PN - create news statistics, $VER"
    exit 1
}

Msg () {
    for MsgLine
    do echo "$PN: $MsgLine" >&2
    done
}

Fatal () { Msg "$@"; exit 1; }

set -- `getopt h "$@"` || Usage
[ $# -lt 1 ] && Usage			# "getopt" detected an error

while [ $# -gt 0 ]
do
    case "$1" in
					# your flags here
	--)	shift; break;;
	-h)	Usage;;
	-*)	Usage;;
	*)	break;;			# First file name
    esac
    shift
done

Expire=
[ -n "$NextWeek" ] && Expire="$NextWeek"

Tmp="${TMPDIR:=/tmp}/ns$$"
trap 'rm -f "$Tmp" >/dev/null 2>&1' 0
trap "exit 2" 1 2 3 15

if [ $# -ne 1 -o X"$1" != X-f ]
then
    echo "$PN: this script normally is not run from the command line,
	but from cron" >&2
    exit 1
fi

for Group in comp.unix.shell
do
    [ -d "$ArchiveBase/$Group/posters" ] ||
	mkdir -p "$ArchiveBase/$Group/archive"

    nice $HOME/cmds/newstop.new "$Group" > "$Tmp"
    if [ -s "$Tmp" ]
    then
	$MAIL -s "Top 10 posters to $Group" $USER < "$Tmp" &&
	    $MAIL -s "Top 10 posters to $Group" $PUSER < "$Tmp" &&
	    nntppost -f "$PUSER" -S -n "$Group" -t "Top 10 posters $Group" \
	    	-e "$Expire" -o "$Organization" < "$Tmp"
	cp -p "$Tmp" "$ArchiveBase/$Group/archive/posters.$Date"
    fi

    nice $HOME/cmds/newssub "$Group" > "$Tmp"
    if [ -s "$Tmp" ]
    then
	$MAIL -s "Top 10 subjects in $Group" $USER < "$Tmp" &&
	    $MAIL -s "Top 10 subjects in $Group" $PUSER < "$Tmp" &&
	    nntppost -f "$PUSER" -S -n "$Group" -t "Top 10 subjects $Group" \
	    	-e "$Expire" -o "$Organization" < "$Tmp"
	    cp -p "$Tmp" "$ArchiveBase/$Group/archive/subjects.$Date"
    fi
done
exit 0
