#!/bin/sh 

# Original Author: Manoj Srivastava <srivasta@tiamat.datasync.com>

set -e

FLAVOUR=$1
PACKAGE="gnus"

if [ "X$FLAVOUR" = "X" ]; then
    echo Need argument to determine FLAVOUR of emacs;
    exit 1
fi

ELDIR=/usr/share/emacs/site-lisp/$PACKAGE
ELCDIR=/usr/share/$FLAVOUR/site-lisp/$PACKAGE

STARTDIR=/etc/$FLAVOUR/site-start.d
STARTFILE="$PACKAGE-init.el";
STAMPFILE=nnmaildir.elc

case "$FLAVOUR" in
    emacs | emacs20 | emacs19)
	echo "install/$PACKAGE: Ignoring $FLAVOUR."
	;;
    emacs21 | xemacs21 | emacs-snapshot)
	echo -n "install/$PACKAGE: Byte-compiling for $FLAVOUR..."
	if which $FLAVOUR 2>&1 >/dev/null; then
	    echo -n "found $FLAVOUR .."
	else
	    echo "Could not find $FLAVOUR. Exiting"
	    exit 0;
	fi
        if [ -d $ELCDIR ]; then
            if [ -e "${ELCDIR}/${STAMPFILE}" ]; then
                echo "${PACKAGE} files already compiled in ${ELCDIR}." 
                exit 0
            else
	        test -f $ELCDIR/install.log && rm -f $ELCDIR/install.log
                rm -f $ELCDIR/*.elc || true;
                rmdir $ELCDIR
            fi
        fi
        if [ ! -d $ELCDIR ]; then
            install -m 755 -d $ELCDIR
        fi
        cd $ELDIR/lisp

        LOG=`tempfile`;
	trap "test ! -f $LOG || mv -f $LOG  $ELCDIR/install.log > /dev/null 2>&1" EXIT

	make EMACS=/usr/bin/$FLAVOUR > $LOG 2>&1 ;
	COMPILED=$(ls -1 *.elc)
	if [ "X$COMPILED" = "X" ]; then
	    echo >&2 "No compiled files exist!!"
	    echo >&2 "Aborting!!"
	    echo     "No compiled files exist!!"  >> $LOG;
	    echo     "Aborting!!"                 >> $LOG;
	    mv -f $LOG  $ELCDIR/install.log
	    exit 1
	fi

	echo install -m 644 *.elc  $ELCDIR  >> $LOG;
	for file in *.elc; do
	    install      -m 644 $file $ELCDIR;
	done
	mv -f $LOG                 $ELCDIR/install.log;
	chmod 644                  $ELCDIR/install.log;
	rm -f *.elc || true;

 	ucf $ELDIR/lisp/$STARTFILE $STARTDIR/20$STARTFILE;

        echo "done."
	;;
    *)
        echo "install/$PACKAGE: Ignoring emacsen flavor $FLAVOUR.";	
esac
