#!/usr/bin/env python
#
# Copyright (C) 2005-2009 ABINIT Group (Yann Pouillon)
# All rights reserved.
#
# 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 time import gmtime,strftime

import commands
import os
import re
import sys

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

#
# Subroutines
#

# Makefile header
def makefile_header(name,stamp):

 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.
#

""" % (name,stamp,name)



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

#
# Main program
#

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

# Check if we are at the top of the ABINIT source tree
if ( not os.path.exists("configure.ac") or
     not os.path.exists("src/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 in my_configs:
 if ( os.path.exists(cnf) ):
  execfile(cnf)
 else:
  print "%s: Could not find config file (%s)." % (my_name,cnf)
  print "%s: Aborting now." % my_name
  sys.exit(2)

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

# Init
exp_libs = "lib_LIBRARIES ="
exp_dscs = ""

# Process each library
for exp in abinit_exports:

 # Init
 if ( exp in exports_specs ):
  exp_specs = exports_specs[lib]
 else:
  exp_specs = ABI_EXP_NIL

 # Set variables
 exp_libs += " \\\n  lib%s.a" % (exp)
 exp_objs  = "%s_objs =" % (exp)

 # Import source configuration
 for lib in eval("%s_contents" % (exp)):
  # Import blacklist
  try:
    ebl = eval("%s_blacklist" % (exp))
  except:
    ebl = list()

  # Get library contents
  cnf = "src/%s/abinit.src" % (lib)
  if ( os.path.exists(cnf) ):
   execfile(cnf)
  else:
   print "%s: Could not find config file (%s)." % (my_name,cnf)
   print "%s: Aborting now." % my_name
   sys.exit(3)

  # Add objects to the export item
  for src in sources:
   if ( not (src in ebl) ):
    exp_objs += " \\\n  ../%s/%s.$(OBJEXT)" % (lib,src.replace(".F90",""))

 # Library description
 exp_dscs += "# Export: %s\n" % (exp)
 exp_dscs += exp_objs+"\n\n" 
 exp_dscs += "lib%s_a_SOURCES =\n" % (exp)
 exp_dscs += "lib%s_a_LIBADD = $(%s_objs)\n\n" % (exp,exp)

# Finish
exp_libs += "\n\n"

# Output to makefile
mf = file("src/libs/Makefile.am","w")
mf.write(makefile_header(my_name,now)+exp_libs+exp_dscs)
mf.close()
