#! /bin/sh
# /usr/lib/emacsen-common/packages/install/flim
set -e

FLAVOR=$1
PACKAGE=flim

if [ ! -f "/usr/share/$FLAVOR/site-lisp/apel/poem.elc" ]; then exit 0; fi

case $FLAVOR in
    emacs|emacs19|mule2)
    exit 0
    ;;
    *xemacs*)
    mule=`/bin/ls -1 /usr/bin/$FLAVOR*-mule* 2>/dev/null | head -1`
    nomule=`/bin/ls -1 /usr/bin/$FLAVOR*-nomule* 2>/dev/null | head -1`
    if [ -n "$nomule" ]; then
	if [ -n "$mule" ]; then
	    EMACSEN="$mule $nomule"
	else
	    EMACSEN="$nomule"
	fi
    else
	EMACSEN=$FLAVOR
    fi
    ;;
    *)
    EMACSEN=$FLAVOR
    ;;
esac

ELCDIR=/usr/share/$FLAVOR/site-lisp/$PACKAGE
ELDIR=/usr/share/emacs/site-lisp/$PACKAGE
ELCSTAMP=$ELCDIR/compile-stamp
if [ -f "$ELCSTAMP" ]; then
    echo "install/$PACKAGE: already byte-compiled for $FLAVOR, skipped"
    exit 0
fi

LOG=`mktemp -t elc.XXXXXXXXXXXX`
chmod 644 "$LOG"
echo "install/$PACKAGE: byte-compiling for $FLAVOR, logged in $LOG"

cd "$ELDIR"
LINKS=`echo *.el`
if [ ! -d "$ELCDIR" ]; then
    mkdir "$ELCDIR"
    chmod 755 "$ELCDIR"
fi

for EMACS in $EMACSEN; do
    cd "$ELCDIR"
    TOELDIR=../../../emacs/site-lisp/$PACKAGE
    case $EMACS in
	*-nomule*)
	if [ x"$EMACS" != x"$EMACSEN" ]; then
	    if [ ! -d nomule ]; then
		mkdir nomule
		chmod 755 nomule
	    fi
	    cd nomule
	    TOELDIR=../$TOELDIR
	fi
	;;
    esac
    rm -f *.elc __myinit.el
    for f in $LINKS; do
	ln -sf "$TOELDIR/$f" .
    done
    case $EMACS in
	*-nomule*)
	rm -f mel-q-ccl.el mel-b-ccl.el
	;;
    esac
    FILES=`echo *.el | sed s/sasl-xoauth2.el//`

    cat > __myinit.el << EOF
(setq load-path (cons "/usr/share/$FLAVOR/site-lisp/apel" load-path))
(setq load-path (cons "." load-path))
(setq byte-compile-warnings nil)
EOF
    case $EMACS in
	*-nomule*)
	cat >> __myinit.el << EOF
(setq load-path (cons "/usr/share/$FLAVOR/site-lisp/apel/nomule" load-path))
EOF
	;;
	*)
    esac

    FLAGS="-q -no-site-file -batch -l __myinit.el -f batch-byte-compile"
    echo "$EMACS" $FLAGS $FILES >> "$LOG"
    "$EMACS" $FLAGS $FILES >> "$LOG" 2>&1
    chmod 644 *.elc

    rm -f __myinit.el*
done # EMACS in $EMACSEN

echo "install/$PACKAGE: deleting $LOG"
rm -f "$LOG"

echo "install/$PACKAGE: byte-compiling for reverse dependency"
pkgs=
for p in semi w3m-el:w3m w3m-el-snapshot:w3m mu-cite rail lsdb elserv; do
    pkg=`echo $p | cut -d : -f 1`
    sname=`echo $p | cut -d : -f 2`
    dir=/usr/share/$FLAVOR/site-lisp/$sname
    if [ -n "$sname" ] && [ -d "$dir" ] && [ -f "/usr/lib/emacsen-common/packages/install/$pkg" ]; then
	rm -f "$dir"/*.elc "$dir"/*/*.elc "$dir"/*-stamp "$dir"/*/*-stamp
	pkgs="$pkg $pkgs"
    fi
done
for pkg in $pkgs; do
    "/usr/lib/emacsen-common/packages/install/$pkg" "$FLAVOR"
done

touch "$ELCSTAMP"
exit 0
