#!/bin/bash
#
#  Monkey HTTP Daemon
#  ------------------
#  Copyright (C) 2001-2009, Eduardo Silva P.
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU Library General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

VERSION="0.11.1"
SYSNAME=`uname -s`
SYSINFO=`uname -sr`

INCDIR="src/include/"

messages_en()
{
	case "$*" in
		"1")
			echo "+ Creating conf/monkey.conf"
		;;
		"2")
			echo "+ Creating Makefile"
		;;
		"3")
			echo "+ Creating src/Makefile"
		;;
		"4")
			echo "+ Creating src/include/info.h"
		;;
		"5")
			echo "+ Creating banana script"
		;;
		"6")
			echo -n "Configuration done, just type 'make' to build or 'make help"
		;;
		"7")
			echo -n "+ Checking for Pthreads lib.........."
		;;
	esac
}

# Create configuration files under 'conf/'
make_conf()
{
cat $INCDIR/config.path lang/"$*"/mconf lang/"$*"/sites/default > makeconf.sh
chmod 755 makeconf.sh
./makeconf.sh
rm makeconf.sh
rm $INCDIR/config.path
}

local_dirs()
{
bin="bin"
logs="logs"
sites="conf/sites"

if [ ! -d $bin ]; then
    mkdir $bin
fi

if [ ! -d $logs ]; then
    mkdir $logs
fi

if [ ! -d $sites ]; then
    mkdir $sites
fi

}

main()
{
	local_dirs
	dir=0
	actual_path=`pwd`

	if [ "$prefix" != "$actual_path" ]; then
		dir=1
	fi

	if [ "$bindir" != "$actual_path/bin" ]; then
		dir=1
	fi

	if [ "$cgibin" != "$actual_path/cgi-bin" ]; then
		dir=1
	fi

	if [ "$sysconfdir" != "$actual_path/conf" ]; then
		dir=1
	fi

	if [ "$datadir" != "$actual_path/htdocs" ]; then
		dir=1
	fi

	if [ "$logdir" != "$actual_path/logs" ]; then
		dir=1
	fi

        echo
	echo "Checking dependencies"
        echo "====================="
        echo
	messages_$lang "7"
	check_lib lang

        echo
        echo "Creating Makefiles and scripts"
        echo "=============================="
        echo

	messages_$lang "1"
	create_conf prefix bindir cgibin sysconfdir datadir logdir

	make_conf  $lang
	messages_$lang "2"

	if [ "$dir" = 0 ]; then
		create_makefile1 bindir
	else
		create_makefile1_install prefix bindir cgibin sysconfdir datadir logdir
	fi

	messages_$lang "3"
	create_makefile2 mod_libs mod_obj make_script add_obj_mod cheetah_obj

	messages_$lang "4"
	create_info sysconfdir SYSNAME VERSION

	messages_$lang "5"
	create_banana_script bindir logdir
	echo
	messages_$lang "6"

	if [ "$dir" = 1 ]; then
		echo -n " && make install' "
	else
		echo "' "
	fi
	echo

        create_makefile_plugins $plugdir

	echo "#define CC \"${CC}\"" > src/include/env.h
}

# Check pthreads lib
check_lib()
{
cat > check.c <<EOF
#include <pthread.h>
int main(){ return 0;}
EOF

libtest=`gcc check.c -lpthread &>configure.log`
libstatus=`cat configure.log`
if  test -n "$libstatus"  ; then
	echo "no"
	rm -fr check* configure.log
	exit 1
fi
echo "yes"
rm -fr check* configure.log a.out
}


# Create Makefile
create_makefile1()
{
cat > Makefile << EOF
# Monkey HTTP Daemon: Makefile
# ============================
default:
	@(cd src; \$(MAKE) all)

plugins:
	@(cd plugins; \$(MAKE) all)

monkeyversion:
	@echo $VERSION

help:
	@echo "Make help:"
	@echo "  plugins       - Build webserver's plugins"
	@echo "  monkeyversion - Output the webserver's version"
	@echo "  clean         - Remove generated binary files"
	@echo "  distclean     - Clean plus configuration and Make files"
	@echo " "
	@echo "Execute 'make' to build the webserver."

clean:
	@(cd src; \$(MAKE) clean)
distclean:
	@(cd src; \$(MAKE) distclean)
EOF
}

create_makefile1_install()
{
# Look for plugins and create list
for entry in plugins/*
do
        if [ -d $entry ]; then
	    echo -e "\tinstall -s -m 644 $entry/*.so \${PLUGINDIR}" >> plugins.list
        fi
done;
plglist=`cat plugins.list`
rm -rf plugins.list

# Look for plugins configuration
for entry in conf/plugins/*
do
	if [ -d $entry ]; then
	    echo -e "\tcp -r $entry \${SYSCONFDIR}/plugins/" >> plugins.conf
	fi
done;
plgconf=`cat plugins.conf`
rm -rf plugins.conf

cat > Makefile <<EOF
# Monkey HTTP Daemon: Makefile
# ============================
PREFIX=\$(DESTDIR)${prefix}
BINDIR=\$(DESTDIR)${bindir}
CGIBIN=\$(DESTDIR)${cgibin}
SYSCONFDIR=\$(DESTDIR)${sysconfdir}
DATADIR=\$(DESTDIR)${datadir}
LOGDIR=\$(DESTDIR)${logdir}
PLUGINDIR=\$(DESTDIR)${plugdir}

default:
	@(cd src; \$(MAKE) all)
clean:
	@(cd src; \$(MAKE) clean)
distclean:
	@(cd src; \$(MAKE) distclean)

install:
	\$(MAKE) -C src all
	install -d \$(BINDIR)
	install -d \$(CGIBIN)
	install -d \$(SYSCONFDIR)
	install -d \${SYSCONFDIR}/sites
	install -d \${SYSCONFDIR}/plugins
	install -d \$(DATADIR)
	install -d \${DATADIR}/imgs
	install -d \${DATADIR}/php
	install -d \${DATADIR}/docs
	install -d \${LOGDIR}
	install -d \${PLUGINDIR}
	install -m 755 bin/monkey \$(BINDIR)
	install -m 755 bin/banana \$(BINDIR)
	install -m 644 ./conf/*.* \$(SYSCONFDIR)
$plgconf
	install -m 644 ./conf/sites/* \${SYSCONFDIR}/sites
$plglist
	install -m 644 ./htdocs/*.* \$(DATADIR)
	install -m 644 ./htdocs/imgs/*.* \${DATADIR}/imgs
	$STRIP \$(BINDIR)/monkey
	$STRIP \${PLUGINDIR}/*
	@echo
	@echo  " Running Monkey :"
	@echo  " ----------------"
	@echo
	@echo  "  # $bindir/monkey"
	@echo
	@echo  "  For more help use '-h' option"
	@echo

EOF
}

# Create monkey/src/Makefile
create_makefile2()
{

cat > src/Makefile<<EOF
CC	= $CC
CFLAGS	= $CFLAGS
DEFS    = $DEFS
INCDIR  = ./include
LDFLAGS	=
DESTDIR	= ../bin/monkey
LIBS	= -ldl -lpthread $mod_libs $MORE_LIBS
OBJ	= monkey.o method.o mimetype.o request.o \\
	header.o config.o signals.o \\
	user.o utils.o chars.o epoll.o scheduler.o \\
	str.o memory.o connection.o iov.o http.o \\
	file.o socket.o clock.o cache.o worker.o \\
	server.o plugin.o \\
        $add_obj_mod

all: ../bin/monkey

../bin/monkey: \$(OBJ)
	@echo
	@echo "Compiling Monkey"
	@echo "================"
	\$(CC) \$(CFLAGS) \$(DEFS) \$(LIBS) \$(LDFLAGS) -o \$@ \$(OBJ) $mod_obj
	@echo
	@echo "Compiling Plugins"
	@echo "================="
	@(cd ../plugins && \$(MAKE) all && cd ..)

clean:
	rm -rf *.o
	rm -rf ../bin/monkey

distclean:
	rm -rf *.o ../bin/* Makefile \\
	../Makefile ../conf/monkey.conf \\
	../conf/sites/* include/info.h ../logs/*\\

.c.o:
	\$(CC) -c \$(CFLAGS) \$(DEFS) -I\$(INCDIR) \$<
EOF
}

create_makefile_plugins()
{
    cd plugins
    cat > Makefile <<EOF
all:
EOF
    dir=`pwd`
    plugins_load="../conf/plugins.load"
    echo -n > $plugins_load
    echo "# Monkey Plugins Loader" >> $plugins_load
    echo "# =====================" >> $plugins_load
    echo "# Monkey plugins are extended functionalities for Monkey," >> $plugins_load
    echo "# the main directive to load a plugin is LoadPlugin plus" >> $plugins_load
    echo "# the absolute path for the desired plugin." >> $plugins_load
    echo "#" >> $plugins_load
    echo "# Please check the following list of available plugins:" >> $plugins_load
    echo "" >> $plugins_load
    echo "[PLUGINS]" >> $plugins_load
    echo "" >> $plugins_load

    for plugin_dir in `echo */ "" | sed "s/\/ /\n/g"`;
    do
        comment="    "
	if test -e $plugin_dir/DISABLED ; then
            continue
	fi

        if test -e $plugin_dir/MANDATORY ; then
	    comment="    "
        fi

        if test -e $plugin_dir/OPTIONAL ; then
            comment="    # "
	fi

        echo "	@(cd $plugin_dir && \$(MAKE) && cd ..)" >> Makefile;
        sed -e "s|\$CC|$CC|" -e "s/\$CFLAGS/$CFLAGS/" -e "s/\$DEFS/$DEFS/" $plugin_dir/Makefile.in > $plugin_dir/Makefile

        if test -e $plugin_dir/ABOUT ; then
            cat $plugin_dir/ABOUT | sed -e 's/^/    # /' >> ../conf/plugins.load
	    echo "    #" >> ../conf/plugins.load
	else
	    echo "    #" >> ../conf/plugins.load
	fi

	if [ "$plugdir" != "" ]; then
	    echo "${comment}Load $plugdir/monkey-$plugin_dir.so" >> ../conf/plugins.load
	else
	    echo "${comment}Load $dir/$plugin_dir/monkey-$plugin_dir.so" >> ../conf/plugins.load
	fi

	echo "" >> ../conf/plugins.load
    done

# Add 'install' option to Makefile if plugdir was specified
if [ "$plugdir" != "" ]; then
    echo -e "\ninstall:" >> Makefile
    echo -e "\tinstall -d $plugdir" >> Makefile

    list=`echo */ "" | sed "s/\/ /\n/g"`
    for i in $list;
	do
	      echo -e "\tinstall -m 644 $dir/$i/monkey-$i.so $plugdir/" >> Makefile
	done
fi
    cd ..
}

# Creando include/info.h
create_info()
{
cat > $INCDIR/info.h <<EOF
#define OS "$SYSNAME"
#define VERSION "$VERSION" /* Version de Monkey */
#define MONKEY_PATH_CONF "$sysconfdir"
EOF
}

create_conf()
{
cat > $INCDIR/config.path <<EOF
#!/bin/sh
prefix=$prefix
bindir=$bindir
cgibin=$cgibin
sysconfdir=$sysconfdir
datadir=$datadir
logdir=$logdir
EOF
}

create_banana_script()
{
cat > bin/banana << EOF
#!/bin/sh
#
# Monkey HTTP Daemon - Banana Script
# -----------------------------------
# This script allow you to control monkey. Written by Eduardo Silva
# ----------------------------
# Date		: 2002/09/01.
# ----------------------------
#
# Use: ./banana OPTION
#
# Options available to banana:
#
#	start	->	start monkey
#	restart	->	restart monkey
#	stop	->	stop monkey if this is running
#	help	->	what do u think ?

PIDFILE="$logdir/monkey.pid"
BINMONKEY="$bindir/monkey"

for arg in \$*; do
	case "\$arg" in
		-*=*) optarg=\`echo "\$arg" | sed 's/[-_a-zA-Z0-9]*=//'\` ;;
		   *) optarg= ;;
	esac

	if  ! test -f \$PIDFILE ; then
		STATUS="no"
	else
		PIDMONKEY=\`cat \$PIDFILE\`
		if ! kill -0 \$PIDMONKEY 2>/dev/null; then
			STATUS="no"
		else
			STATUS="yes"
		fi
	fi

	case "\$arg" in
		start)
			if [ "\$STATUS" = "yes"  ] ; then
				echo "Monkey is running... (PID=\$PIDMONKEY)"
				exit 1
			fi
			if ! test -x \$BINMONKEY ; then
				echo "Error: I can't run binary file"
				exit 1
			else
				if \$BINMONKEY -D  2>/dev/null ; then
					echo "Running Monkey -> OK"
					exit 0
				fi
			fi
		;;
		stop)
			if  [ "\$STATUS" = "no" ]; then
				echo "Monkey is not running."
				exit 1
			fi
			kill -9 \$PIDMONKEY
			rm -rf \$PIDFILE > /dev/null
			echo "Monkey stopped (\$PIDMONKEY)"
			exit 0
			;;
		restart)
			if  [ "\$STATUS" = "yes" ]; then
				if ! kill \$PIDMONKEY  > /dev/null ; then
					killall -9 monkey
				else
					echo -n "Stopping Monkey... "
				fi
			else
				echo -n "Monkey is not running... "
			fi
			if ! test -x \$BINMONKEY ; then
				echo "Error: I can't run binary file"
				exit 1
			else
				\$BINMONKEY -D > /dev/null
				echo "Restarting -> OK"
				exit 0
			fi
			;;
		*)
			echo "Use : banana [start|stop|restart|help]"
			exit 1
		;;
	esac
done
echo "Use : banana [start|stop|restart|help]"

exit 0
EOF
chmod 755 bin/banana
}

#---------------------------#
# End Functions
#---------------------------#


#---------------------------#
# Starting configure
#---------------------------#
aux=`pwd`

prefix="$aux"
bindir="$aux/bin"
cgibin="$aux/cgi-bin"
sysconfdir="$aux/conf"
datadir="$aux/htdocs"
logdir="$aux/logs"
plugdir=""

for arg in $*; do
	case "$arg" in
		-*=*)
			optarg=`echo "$arg" | sed 's/[-_a-zA-Z0-9]*=//'` ;;
		   *) optarg= ;;
	esac

	case "$arg" in
		--prefix*)
			prefix=$optarg
			bindir="$optarg/bin"
			cgibin="$optarg/cgi-bin"
			sysconfdir="$optarg/conf"
			datadir="$optarg/htdocs"
			logdir="$optarg/logs"
                        plugdir="$optarg/plugins"
			;;
		--bindir*)
			bindir=$optarg
			;;
		--cgibin*)
			cgibin=$optarg
			;;
		--sysconfdir*)
			sysconfdir=$optarg
			;;
		--datadir*)
			datadir=$optarg
			;;
		--logdir*)
			logdir=$optarg
			;;
                --plugdir*)
                        plugdir=$optarg
                        ;;
		--debug*)
			debug=1
			;;
		--trace*)
			trace=1
			;;
		--version*)
			echo "Monkey HTTP Daemon v$VERSION"
			echo "-------------------------"
			echo "Copyright 2001-2010"
			echo "Developed by Eduardo Silva Pereira"
			echo "Monkey Home   : http://www.monkey-project.com"
			echo "Contact Email : edsiper@gmail.com"
			echo
			exit 1
			;;
		*)
			echo "Usage: configure [--prefix=PREFIXDIR] [ --bindir=BINDIR]"
			echo "                 [--sysconfdir=SYSCONFDIR] [--datadir=DATADIR]"
                        echo "                 [--logdir=LOGDIR] [--plugdir=PLUGDIR]"
			echo
			echo "Options: "
			echo "  --help		  Display this help and exit"
			echo "  --version		  Display version information and exit"
			echo "  --debug		  Compile Monkey with debugging symbols"
			echo "  --trace		  Compile Monkey with trace messages (don't use in production)"
			echo
			echo "  --prefix=PREFIX	  Install Monkey under PREFIX directory"
			echo "  --bindir=BINDIR	  Install Monkey binaries under BINDIR directory"
			echo "  --sysconfdir=SYSCONFDIR Install Monkey conf files under SYSCONFDIR dir"
			echo "  --datadir=DATADIR	  Install Monkey data dir files under DATADIR directory"
			echo "  --logdir=LOGDIR	  Install Monkey log files under LOGDIR directory"
			echo "  --plugdir=PLUGDIR	  Target directory for Monkey plugins"
			echo
			exit 1
			;;
	esac
done

echo "********************************************"
echo "        Monkey HTTP Daemon v$VERSION        "
echo "*       http://www.monkey-project.com      *"
echo "* ---------------------------------------- *"
echo "*  We need beta testers, developers and    *"
echo "* translators!, if you want to contribute  *"
echo "* to this wonderful project contact us !   *"
echo "*                                          *"
echo "*        irc.freenode.net #monkeyd         *"
echo "*                                          *"
echo "*         Thanks for use Monkey!!!         *"
echo "*                                          *"
echo "********************************************"
echo "System   : $SYSINFO"

lang="en"


# Configure environment
if test -z "$CC" ; then
    gcc_path=`which gcc`
    if test -x "$gcc_path" ; then
        CC="gcc"
    else
        echo "I'm a Monkey not a compiler! how do you suppose to compile me ? Install a compiler"
        exit 1
    fi
fi

if test -z "$STRIP" ; then
    STRIP="strip"
fi

if test -z "$debug" ; then
    CFLAGS="$CFLAGS -O2 -Wall"
else
    CFLAGS="$CFLAGS -g -Wall"
fi

if [ $trace ] ; then
    DEFS="-DTRACE"
fi

# Starting main function
main prefix lang bindir cgibin sysconfdir datadir logdir plugdir modules SYSNAME VERSION
exit 0
