#! /bin/sh -e
#  /usr/lib/emacsen-common/packages/install/foo
# [ This particular script hasn't been tested, so be careful. ]

set -e

FLAVOR=$1
PACKAGE="wl"

if [ "X${FLAVOR}" = "X" ]; then
    echo Need argument to determin FLAVOR of emacs;
    exit 1
fi

if [ "X${PACKAGE}" = "X" ]; then
    echo Internal error: need package name;
    exit 1;
fi

if [ ${FLAVOR} = xemacs21 ]; then
   XEMACS=`ls /usr/bin/xemacs*21*-mule* 2> /dev/null | head -1`
   if [ -z $XEMACS ]; then exit 0; fi
   EMACS=`basename $XEMACS`
else
   EMACS=${FLAVOR}
fi

ELDIR=/usr/share/emacs/site-lisp/${PACKAGE}
ELCDIR=/usr/share/${FLAVOR}/site-lisp/${PACKAGE}

SITELISP=/usr/share/${FLAVOR}/site-lisp

EFLAGS="-batch -q -l ./path.el"
COMPILE="-batch -q -f batch-byte-compile"

case "${FLAVOR}" in
	emacs|emacs19)
	;;
	*)

	if [ -e /usr/lib/emacsen-common/packages/install/wemi ]; then
		 if [ ! -d ${SITELISP}/semi ] ; then
		/usr/lib/emacsen-common/packages/install/wemi ${FLAVOR}
		 fi
	fi

	echo -n "install/${PACKAGE}: Byte-compiling for ${FLAVOR} ..."
	if [ "${FLAVOR}" = "mule2" ]; then
		if [ ! -d /usr/share/emacs/site-lisp/clime ]; then
		echo " exited."
		echo "W: Please install \`clime' package for mule2." ;
		exit 0;
		fi
	else
		if [ ! -d /usr/share/emacs/site-lisp/flim ]; then
		echo " exited."
		echo "W: Please install \`flim' package for ${FLAVOR}." ;
		exit 0;
		fi
	fi

    rm -rf ${ELCDIR}
    install -m 755 -d ${ELCDIR}

    (cd ${ELDIR}
cat << EOF > path.el
(setq load-path (cons (concat "/usr/share/${FLAVOR}/site-lisp/apel") load-path))
(setq load-path (cons (concat "/usr/share/${FLAVOR}/site-lisp/flim") load-path))
(setq load-path (cons (concat "/usr/share/${FLAVOR}/site-lisp/semi") load-path))
EOF
        make EMACS=${EMACS} FLAGS="${EFLAGS}" LISPDIR=${SITELISP} \
			PIXMAPDIR=${ELCDIR}/icons \
			> ${ELCDIR}/CompilationLog 2>&1
        make EMACS=${EMACS} FLAGS="${EFLAGS}" LISPDIR=${SITELISP} install \
			PIXMAPDIR=${ELCDIR}/icons \
			>> ${ELCDIR}/CompilationLog 2>&1
        make EMACS=${EMACS} FLAGS="${EFLAGS}" LISPDIR=${SITELISP} clean \
			PIXMAPDIR=${ELCDIR}/icons \
			>> ${ELCDIR}/CompilationLog 2>&1
		rm -fr path.el ${ELCDIR}/*.el ${ELCDIR}/icons
	(cd ${ELDIR}/utils/ && \
	    ${EMACS} --eval '(setq load-path (cons "." load-path))' \
	    	${COMPILE} *.el >> ${ELCDIR}/CompilationLog 2>&1 && \
	 mv *.elc ${ELCDIR})
	rm -f wl/*.elc elmo/*.elc
	)

	gzip -9 ${ELCDIR}/CompilationLog

	echo " done."
	;;
esac

exit 0;
