#!/usr/bin/env python
#
# Copyright (C) 2005-2012 ABINIT Group (Yann Pouillon)
#
# This file is part of the ABINIT software package. For license information,
# please see the COPYING file in the top-level directory of the ABINIT source
# distribution.
#

from ConfigParser import ConfigParser,NoOptionError
from time import gmtime,strftime

import commands
import os
import re
import sys

class MyConfigParser(ConfigParser):

  def optionxform(self,option):
    return str(option)

# ---------------------------------------------------------------------------- #

#
# Subroutines
#

# Makefile header
def makefile_template(name,stamp,b_name):

  return """#
# Makefile for ABINIT                                      -*- Automake -*-
# Generated by %s on %s

#
# IMPORTANT NOTE
#
# Any manual change to this file will systematically be overwritten.
# Please modify the %s script or its config file instead.
#

# Delegate build to bindings' own Makefile
all_targets all: bindings-ready

if DO_BUILD_BINDINGS
bindings-ready:
	$(MAKE) -f $(top_srcdir)/bindings/%s/%s.mk \
	  srcdir="$(srcdir)" abinit_srcdir="$(abinit_srcdir)" \
	  abinit_builddir="$(abinit_builddir)" \
	  INSTALL="$(INSTALL)" AR="$(AR)" ARFLAGS="$(ARFLAGS)" \
	  RANLIB="$(RANLIB)" @SET_MAKE@
	@touch bindings-ready
else
bindings-ready:
	@echo "Support for bindings has been disabled"
	@touch bindings-ready
endif

clean-local:
	$(MAKE) -f $(top_srcdir)/bindings/%s/%s.mk clean \
	  srcdir="$(srcdir)" abinit_srcdir="$(abinit_srcdir)" \
	  abinit_builddir="$(abinit_builddir)" @SET_MAKE@

EXTRA_DIST = @SOURCES@

CLEANFILES = @CLEANS@ \\
  bindings-ready
""" % (name,stamp,name,b_name,b_name,b_name,b_name)



# ---------------------------------------------------------------------------- #

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-bindings"
my_configs = ["config/specs/bindings.conf"]

# Check if we are in the top of the ABINIT source tree
if ( not os.path.exists("configure.ac") or
     not os.path.exists("src/98_main/abinit.F90") ):
  print "%s: You must be in the top of an ABINIT source tree." % my_name
  print "%s: Aborting now." % my_name
  sys.exit(1)

# Read config file(s)
for cnf_file in my_configs:
  if ( os.path.exists(cnf_file) ):
    if ( re.search("\.cf$",cnf_file) ):
      execfile(cnf_file)
  else:
    print "%s: Could not find config file (%s)." % (my_name,cnf_file)
    print "%s: Aborting now." % my_name
    sys.exit(2)

# What time is it?
now = strftime("%Y/%m/%d %H:%M:%S +0000",gmtime())

# Init
cnf = MyConfigParser()
cnf.read(my_configs[0])
abinit_bindings = cnf.sections()
abinit_bindings.sort()

# Process each bindings blob
for bnd in abinit_bindings:

  # Init
  bnd_dir = "bindings/%s" % (bnd)
  sources = ""
  cleans = ""
  sep = " \\\n  "

  # Extract bindings information
  try:
    bnd_bins = cnf.get(bnd,"binaries").split()
  except NoOptionError:
    bnd_bins = None
  try:
    bnd_hdrs = cnf.get(bnd,"headers").split()
  except NoOptionError:
    bnd_hdrs = None
  try:
    bnd_libs = cnf.get(bnd,"libraries").split()
  except NoOptionError:
    bnd_libs = None
  try:
    bnd_mods = cnf.get(bnd,"modules").split()
  except NoOptionError:
    bnd_mods = None
  try:
    bnd_srcs = cnf.get(bnd,"sources").split()
  except NoOptionError:
    bnd_srcs = None

  # Update list of files to clean
  if ( bnd_bins != None ):
    cleans += sep+sep.join(bnd_bins)
  if ( bnd_hdrs != None ):
    cleans += sep+sep.join(bnd_hdrs)
  if ( bnd_libs != None ):
    cleans += sep+sep.join(bnd_libs)
  if ( bnd_mods != None ):
    cleans += sep+sep.join(bnd_mods)
  if ( bnd_srcs != None ):
    sources += sep+sep.join(bnd_srcs)

  # Import and update template 
  makefile = makefile_template(my_name,now,bnd)
  makefile = re.sub("@SOURCES@",sources,makefile)
  makefile = re.sub("@CLEANS@",cleans,makefile)

  # Add additional hand-written information
  add = bnd_dir+"/abinit.amf"
  if ( os.path.exists(add) ):
    makefile += "\nEXTRA_DIST += abinit.amf\n"
    makefile += "\n"+file(add,"r").read()

  # Add RoboDOC header
  hdr = "%s/_%s_" % (bnd_dir,bnd)
  if ( os.path.exists(hdr) ):
    makefile += "\nEXTRA_DIST += _%s_\n" % (bnd)

  mf = file(bnd_dir+"/Makefile.am","w")
  mf.write(makefile)
  mf.close()
