#!/bin/sh
#
#	aegis - project change supervisor
#	Copyright (C) 2004, 2006, 2008 Peter Miller
#
#	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 3 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 General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with this program. If not, see
#	<http://www.gnu.org/licenses/>.
#
bindir=/usr/pkg/bin

#
# read command line arguments
#
symlink=no
quiet=no
while test $# -gt 0
do
    case "$1" in
    -s)
	symlink=yes
	;;
    -q)
	quiet=yes
	;;
    *)
	echo "Usage: $0 [ -s ][ -q ]" 1>&2
	exit 1
	;;
    esac
    shift
done

#
# Look for the httpd config files, so that we can find where to
# put the CGI script, and other HTML files.
#
_cv_web=no
_cv_httpd=no
for ac_dir in \
    /etc/apache \
    /etc/httpd \
    /opt/apache \
    /opt/httpd \
    /usr/apache \
    /usr/httpd \
    /usr/local/apache \
    /usr/local/apache/etc \
    /usr/local/etc/apache \
    /usr/local/etc/httpd \
    /usr/local/httpd \
    /usr/local/httpd/etc \
    /var/apache \
    /var/httpd \
    /var/lib/apache \
    /var/lib/httpd
do
    if test -r $ac_dir/conf/httpd.conf -o -r $ac_dir/httpd.conf
    then
       	_cv_web=yes
       	_cv_httpd=$ac_dir
       	break
    fi
done

if test "$_cv_web" != "yes"
then
    echo "Web server configuration file not found." 1>&2
    exit 1
fi

_cv_ScriptAlias=no
for f in $_cv_httpd/conf/srm.conf $_cv_httpd/conf/httpd.conf \
    $_cv_httpd/srm.conf $_cv_httpd/httpd.conf
do
    if test -r $f
    then
	tmp=`awk '/^[ 	]*ScriptAlias.*cgi-bin/{ \
	    dir=$3;				\
	    sub(/"/, "", dir);			\
	    sub(/"/, "", dir);			\
	    sub(/\/*$/, "", dir);		\
	    print dir				\
	    }' $f | head -1`
	test "x$tmp" != "x" && _cv_ScriptAlias="$tmp"
    fi
done

if test "$_cv_ScriptAlias" = "no"
then
    echo "No ScriptAlias found in $_cv_httpd/conf/httpd.conf" 2>&1
    exit 1
fi

#
# Remove thatever is there at the moment.
#
test "$quiet" = "no" && echo rm $_cv_ScriptAlias/aeget
rm -f $_cv_ScriptAlias/aeget

if test "$symlink" = "yes"
then
    #
    # Put a symbolic link from the cgi-bin directory to aeget.
    #
    test "$quiet" = "no" && \
    echo ln -s $bindir/aeget $_cv_ScriptAlias/aeget
    ln -s $bindir/aeget $_cv_ScriptAlias/aeget
    test "$?" != 0 && exit 1
else
    #
    # Copy aeget into the cgi-bin directory.
    #
    test "$quiet" = "no" && \
    echo cp $bindir/aeget $_cv_ScriptAlias/aeget
    cp $bindir/aeget $_cv_ScriptAlias/aeget
    test "$?" != 0 && exit 1
fi

#
# Report success.
#
test "$quiet" = "no" && echo "Done."
exit 0
