#! /usr/bin/env python
#
# $Id: configure 6952 2009-12-05 00:23:47Z robin $

import os
import os.path
import sys
import stat
import subprocess

Prefix = "/usr/local/bro"  # match Bro's default.
BroDist = os.path.abspath("../..")
BroCtlSrc = os.path.join(BroDist, "aux/broctl")
BroBuild = BroDist
BroCtlBuild = os.path.join(BroDist, "aux/broctl")
StandAlone = False

def usage():
    print """
Usage: ./configure [--prefix=<dir>] [--brodist=<dir>] [--standalone]

     --prefix=<dir>    Base directory for cluster installation [Default: %s]
     --brodist=<dir>   Base directory of Bro distribution      [Default: %s]

     --standalone      Do a non-cluster, one-Bro-only installation
""" % (Prefix, BroDist)
    sys.exit(1)

args = {}
for arg in sys.argv[1:]:
    try:
        m = arg.find("=")
        if m >= 0: 
            opt = arg[0:m].strip()
	    val = arg[m+1:].strip()
        else:
            opt = arg.strip()
            val = None

        if opt == "--prefix" and val:
            if val != "NONE":
                Prefix = os.path.abspath(val)
                
        elif opt == "--brodist" and val:
            BroDist = os.path.abspath(val)
            BroCtlSrc = os.path.join(BroDist, "aux/broctl")
            
        elif opt == "--builddir" and val:
            BroCtlBuild = os.path.abspath(val)
            BroBuild = os.path.abspath(os.path.join(BroCtlBuild, "../.."))
                    
        elif opt == "--standalone":
            StandAlone = True
        else:
            usage()

        args[opt] = val

    except ValueError:
        usage()

Version = open(os.path.join(BroDist, "aux/broctl/VERSION")).readline().strip()

try:
    p = subprocess.Popen("svnversion", stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)
    (stdin, stdout) = (p.stdin, p.stdout)
    stdin.close()
    svnversion = stdout.readline().split()[0]
    if svnversion != "exported":
        Version += " [r%s]" % svnversion
except:
    pass
        
bin = os.path.join(BroCtlBuild, "bin")        
if not os.path.exists(bin):
    os.mkdir(bin)
        
# Create Makefile, bin/broctl and bin/make-env by replacing configuration variables.
for file in ("Makefile", "bin/broctl", "bin/make-wrapper"):

    src = os.path.join(BroDist, "aux/broctl/%s.in" % file)
    dst = os.path.join(BroCtlBuild, file)

    try:
        os.unlink(dst)
    except OSError:
        pass

    out = open(dst, "w")
    
    for line in open(src):
        line = line.replace("$PREFIX", Prefix)
        line = line.replace("$BRODIST", BroDist)
        line = line.replace("$BROBUILD", BroBuild)
        line = line.replace("$BROCTLBUILD", BroCtlBuild)
        line = line.replace("$BROCTLSRC", BroCtlSrc)
        line = line.replace("$STANDALONE", StandAlone and "True" or "False")
        line = line.replace("$VERSION", Version)
        print >>out, line, 

    # Copy the mode of the source file but remove write permission 
    # to prevent accidental modifications.
    mode = os.stat(src).st_mode
    os.chmod(dst, mode &~ 0222)

    print "Created %s." % file

# Create config.status.
status = os.path.join(BroCtlBuild, "config.status")
out = open(status, "w")
print >>out, """#! /bin/sh
# Generated by configure.
# Run this file to recreate the current configuration.
echo Recreating configuration.
echo

if [ -e ./BroControl ]; then
    configure=./configure
    args["--brodist"] = "../../"
else
    configure=%s/configure
fi

$configure %s && exit
""" % (BroCtlSrc, " ".join(["%s=%s" % (k, v) for (k, v) in args.items()]))

os.chmod(status, 0750)

# Done.

print """
            Bro Control Configuration Summary
==========================================================

   Installation directory:      %s
   Bro distribution:            %s
   Bro build directory:         %s
   Bro Control distribution:    %s
   Bro Control build directory: %s
   
   Standalone installation:     %s

""" % (Prefix, BroDist, BroBuild, BroCtlSrc, BroCtlBuild, (StandAlone and "yes" or "no"))














