#!/bin/bash
# Shell script to assist with building ircd-hybrid modules and installing
# them into the correct dirs so they can be modloaded.
# (c) 2003 by Joshua Kwan. Licensed under the GNU GPL,
# see /usr/share/common-licenses/GPL on Debian systems.
#
# Syntax: mbuild-hybrid [-s m_modsource.c] [-p outputpath] [-o misc-cflags]

OUTPATH=/usr/lib/ircd-hybrid/modules
CFLAGS="-O2 -g -Wall "
until [ -z "$1" ]
do
	case "$1" in
		-s) MODSOURCE=$2; shift; shift;;
		-p) OUTPATH=$2; shift; shift;;
		-o) CFLAGS+=$2; shift; shift;;
		--help)
			echo "usage: mbuild-hybrid [-s m_modsource.c] [-p outputpath] [-o misc-cflags]"
			exit 0
		;;
	esac
done	

if [ -z $MODSOURCE ]; then
	echo "error: no source file specified"
	exit 1
fi

if [ ! -d "/usr/include/ircd-hybrid-8" ]; then
	echo "error: where are the hybrid includes? did you delete them?"
	exit 1
fi

MODNAME=`basename "$MODSOURCE" .c`
MODSOURCE_SO="$MODNAME.so"
echo "Module source file: $MODSOURCE"
echo "Install path: $OUTPATH"
echo "Additional compile flags: $CFLAGS"
echo "--> Compiling: gcc -I/usr/include/ircd-hybrid-8 -fPIC -DPIC -shared $CFLAGS $MODSOURCE -o $MODSOURCE_SO"
gcc -I/usr/include/ircd-hybrid-8 -fPIC -DPIC -shared $CFLAGS "$MODSOURCE" -o "$MODSOURCE_SO" || BUILD_FAILED=1

if [ "$BUILD_FAILED" = "1" ]; then echo "build FAILED, exiting!"; exit 1; fi

echo "--> Installing into $OUTPATH"
if [ "`cd "$OUTPATH" 2>/dev/null && pwd -P`" != "`pwd -P`" ]; then
	mv "$MODSOURCE_SO" "$OUTPATH" || INSTALL_FAILED=1
fi

# ircd-hybrid only loads modules through a libtool .la file, so write one
# next to the .so, as libtool would.
if [ "$INSTALL_FAILED" != "1" ]; then
	cat > "$OUTPATH/$MODNAME.la" <<EOF || INSTALL_FAILED=1
# $MODNAME.la - a libtool library file
# Generated by mbuild-hybrid
dlname='$MODNAME.so'
library_names='$MODNAME.so'
old_library=''
inherited_linker_flags=''
dependency_libs=''
weak_library_names=''
current=0
age=0
revision=0
installed=yes
shouldnotlink=yes
dlopen=''
dlpreopen=''
libdir='$OUTPATH'
EOF
fi

if [ "$INSTALL_FAILED" = "1" ]; then echo "install FAILED, exiting"; exit 1; fi

echo "--> Done!"
echo "To load the module, add this line to /etc/ircd-hybrid/modules.conf"
echo "and rehash the server (/rehash conf):"
echo "  loadmodule \"$MODNAME.la\";"
if [ "`cd "$OUTPATH" 2>/dev/null && pwd -P`" != "/usr/lib/ircd-hybrid/modules" ]; then
	echo "(the server loads modules from module_base_path in that file,"
	echo "/usr/lib/ircd-hybrid/modules by default, not from $OUTPATH)"
fi
