#!/usr/bin/env python
#
# Copyright (C) 2005-2010 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,pkg,pkg_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 package's own Makefile
all_targets all: package-ready

if DO_BUILD_%s  
package-ready:
	$(MAKE) -f $(top_srcdir)/plugins/%s/%s.mk @SET_MAKE@
	-if test -d tmp ; then find tmp -type f -exec mv {} . \; ; rm -rf tmp ; fi
	@touch package-ready
else
package-ready:
	@echo "Support for %s has been disabled"
	@touch package-ready
endif

clean-local:
	$(MAKE) -f $(top_srcdir)/plugins/%s/%s.mk clean @SET_MAKE@
	rm -rf %s tmp
	rm -f dir *.info *.[1-9] *.css *.html

CLEANFILES = \\
  uncompress-stamp \\
  patches-stamp \\
  configure-stamp \\
  build-stamp \\
  install-stamp \\
  package-ready@CLEANS@
""" % (name,stamp,name,pkg.upper(),pkg,pkg,pkg.upper(),pkg,pkg,pkg_name)



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

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-plugins"
my_configs = ["config/specs/plugins.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 plugins
cnf = MyConfigParser()
cnf.read(my_configs[0])
abinit_plugins = cnf.sections()
abinit_plugins.sort()

# Init
sep = " \\\n  "

# Process each library
for pkg in abinit_plugins:

  # Init
  pkg_dir = "plugins/%s" % (pkg)
  cleans  = ""
  patches = list()

  # Extract mandatory package information
  pkg_name = cnf.get(pkg,"name")
  pkg_nick = cnf.get(pkg,"nickname")
  pkg_desc = cnf.get(pkg,"description")
  pkg_urls = cnf.get(pkg,"urls").split()
  pkg_dist = cnf.get(pkg,"distribute")

  # Extract optional package information
  try:
    pkg_bins = cnf.get(pkg,"binaries").split()
  except NoOptionError:
    pkg_bins = None
  try:
    pkg_hdrs = cnf.get(pkg,"headers").split()
  except NoOptionError:
    pkg_hdrs = None
  try:
    pkg_libs = cnf.get(pkg,"libraries").split()
  except NoOptionError:
    pkg_libs = None
  try:
    pkg_mods = cnf.get(pkg,"modules").split()
  except NoOptionError:
    pkg_mods = None

  # Update list of files to clean
  if ( pkg_bins is not None ):
    cleans += sep+sep.join(pkg_bins)
  if ( pkg_hdrs is not None ):
    cleans += sep+sep.join(pkg_hdrs)
  if ( pkg_libs is not None ):
    cleans += sep+sep.join(pkg_libs)
  if ( pkg_mods is not None ):
    cleans += sep+sep.join(pkg_mods)

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

  if ( pkg_dist == "yes" ):
    # Add custom makefile
    makefile += "\nEXTRA_DIST = %s.mk\n" % (pkg)

    # Add existing patches
    for ext in os.listdir(pkg_dir):
      if ( re.search(r"\.patch",ext) ):
        patches.append(ext)
    if ( len(patches) > 0 ):
      patches.sort()
      makefile += "\nEXTRA_DIST +="+sep+sep.join(patches)+"\n"

    # Add additional hand-written information
    add = pkg_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_" % (pkg_dir,pkg)
    if ( os.path.exists(hdr) ):
      makefile += "\nEXTRA_DIST += _%s_\n" % (pkg)

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