#!/usr/bin/env python
#
# Copyright (C) 2005-2022 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 __future__ import print_function, division, absolute_import #, unicode_literals

try:
    from ConfigParser import ConfigParser,NoOptionError
except ImportError:
    from configparser import ConfigParser,NoOptionError
from time import gmtime,strftime

import os
import re
import sys

class MyConfigParser(ConfigParser):

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

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

#
# 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.conf"]

# 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/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)
cnf = MyConfigParser()
for cnf_file in my_configs:
  if ( not os.path.exists(cnf_file) ):
    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.read(my_configs[0])
abinit_exports = cnf.sections()
exp_libs = "lib_LIBRARIES ="
exp_dscs = ""

# Process each library
for exp in abinit_exports:

  # Init
  exp_contents = cnf.get(exp,"contents").split()
  try:
    exp_blacklist = cnf.get(exp,"blacklist").split()
  except NoOptionError:
    exp_blacklist = list()

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

  # Import source configuration
  for lib in exp_contents:

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

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

  # 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 = open("src/libs/Makefile.am", "wt")
mf.write(makefile_header(my_name,now)+exp_libs+exp_dscs)
mf.write("clean-local:\n\trm -f *.a *.la *.so*\n")
mf.close()
