#!/bin/sh
# Post FAQs on demand, and do stuff before and after

# Setup

whatami=`basename $0`			# Get name for diagnostics
co=/usr/local/bin/co			# Use GNU co/ci
ci=/usr/local/bin/ci
unmark=$HOME/sgi-faq/bin/unmark_faq	# Unmarking script
mode=real				# Do real post and unmark
faqs="admin apps audio graphics hardware impressario inventor misc movie performer pointer security"

# Parse args

case "$1" in
-test)
    mode=test				# Do test post and don't unmark
    shift
    ;;
-*)
    echo "$whatami: \"-test\" or nothing!"
    exit 1
    ;;
esac

if [ $# != 0 ]; then
    faqs=$*
fi

faqsd="$faqs diffs"

# Make

cd $HOME/sgi-faq || exit 1
if [ $mode = real ]; then
    echo "Doing 'make install' in $HOME/sgi-faq ..."
    make install || exit 1
else
    echo "Doing 'make test' in $HOME/sgi-faq ..."
    make test || exit 1
fi

# Post

#echo "Posting ..."
#$HOME/lib/post_faq/post_faq.pl -force -config $HOME/lib/post_faq/sgi-faq.$mode -only `echo $faqsd | tr ' ' ,` || exit 1

cd $HOME/sgi-faq/raw || exit 1

# Save FAQs for next diff

if [ $mode = real ]; then
    echo "Saving current FAQs for next diff ..."
    ln -f $faqs ../raw.old	# Can't use || here; "fails" on identical files
fi

# Unmark

echo "Unmarking ..."
for faq in $faqs; do
    if [ ! -r $faq ]; then
	echo "$whatami: $faq is not readable. Skipping ..."
	continue
    fi
    $unmark $faq > $faq.unmarked
    diff $faq $faq.unmarked > /dev/null
    case $? in
    2)  echo "$whatami: diff failed! Skipping ..."
	;;
    0)  echo "$whatami: $faq has no marks. Skipping ..."
	;;
    1)  if [ $mode = real ]; then
	    $co -q -l $faq &&
	    mv $faq.unmarked $faq &&
	    $ci -q -u -m"Unmarked automagically by $whatami." $faq &&
	    echo "$whatami: Unmarked $faq."
	else
	    echo "$whatami: $faq has marks, but we're in test mode. Skipping ..."
	fi
	;;
    esac
    rm -f $faq.unmarked
done

# Check for expired questions

cd $HOME/sgi-faq/real || exit 1
echo "Checking for expired questions ..."
for faq in $faqs; do
    if grep "Subject: -" $faq > /dev/null; then 
        echo "Expired questions in $faq:"
        grep "^Subject: -" $faq
    fi
done
