#! /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="wanderlust2"

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


## Checking MULE supported XEmacs.
if [ ${FLAVOR} = "xemacs20" -o ${FLAVOR} = "xemacs21" ]; then
CHECKMULE=`${FLAVOR} -batch -vanilla -eval "(if (featurep 'mule)(message \"MULE\"))" 2>&1 `
  if [ "${CHECKMULE}" != "MULE" ]; then
		echo
		echo "install/${PACKAGE}: Ignoring ${FLAVOR}."
		echo "${PACKAGE} needs MULE supported XEmacs."
		exit
	fi
fi

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

STARTDIR=/etc/${FLAVOR}/site-start.d
STARTFILE="${PACKAGE}-init.el";

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

EFLAGS="-batch -q"
COMPILE="-batch -q -f batch-byte-compile"

case "${FLAVOR}" in
	emacs)
	;;
	emacs19)
	echo "install/${PACKAGE}: Ignoring ${FLAVOR}."
	;;
	*)

	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}" = "xemacs20" ]; then
		## Fix compile error with xemacs20 on unset LANG or LANG=C .
		export LANG=ja_JP
	fi

	if [ "${FLAVOR}" = "mule2" ]; then
		if [ ! -f /usr/share/emacs/site-lisp/custom-mule-init.el ]; then
		echo " exited."
		echo "W: Please install custom-mule package for mule2." ;
		exit 0;
		fi
	fi

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

    # Byte compile
    (cd ${ELDIR}
        make EMACS=${FLAVOR} FLAGS="${EFLAGS}" ELISPDIR=${SITELISP} \
			> ${ELCDIR}/CompilationLog 2>&1
        make EMACS=${FLAVOR} FLAGS="${EFLAGS}" ELISPDIR=${SITELISP} install \
			>> ${ELCDIR}/CompilationLog 2>&1
        make EMACS=${FLAVOR} FLAGS="${EFLAGS}" ELISPDIR=${SITELISP} clean \
			>> ${ELCDIR}/CompilationLog 2>&1
		rm -f ${ELCDIR}/*.el
		cp utils/*.el ${STARTFILE} ${ELCDIR}
		(cd ${ELCDIR}
			${FLAVOR} ${COMPILE} ${STARTFILE} \
				>> ${ELCDIR}/CompilationLog 2>&1)
		rm -f *.elc elmo/*.elc utils/*.elc
		)

	gzip -9 ${ELCDIR}/CompilationLog

	if [ -e  ${ELCDIR}/${STARTFILE}c ]; then
		mv ${ELCDIR}/${STARTFILE}c ${STARTDIR}/55${STARTFILE}c;
	else
		ln -f -s ${ELDIR}/${STARTFILE} ${STARTDIR}/55${STARTFILE};
	fi
	echo " done."
	;;
esac

exit 0;
