#!/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
except ImportError:
    from configparser import ConfigParser
from time import gmtime,strftime

try:
    from commands import getoutput
except:
    from subprocess import getoutput
import os
import re
import sys

class MyConfigParser(ConfigParser):

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

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

#
# Subroutines
#

# Macro header
def macro_header(name,stamp):

  return """# Generated by %s on %s

#
# Output macros for the "configure" script
#

#
# IMPORTANT NOTE
#
# This file has been automatically generated by the %s
# script. If you try to edit it, your changes will systematically be
# overwritten.
#



# ABI_OUTPUT()
# ------------
#
# Outputs configuration for ABINIT.
#
AC_DEFUN([ABI_OUTPUT],[
  dnl Config files
  AC_CONFIG_FILES([
""" % (name,stamp,name)



# Macro footer
def macro_footer():

  return """
  dnl Output everything
  AC_OUTPUT
]) # ABI_OUTPUT
"""



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

#
# Main program
#

# Initial setup
my_name    = "make-macros-output"
my_configs = {
  "bsys":"config/specs/buildsys.conf",
  "conf":"config/specs/autotools.conf",
  "libs":"config/specs/corelibs.conf"}
my_output  = "config/m4/auto-output.m4"

# 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.values():
  if ( os.path.exists(cnf_file) ):
    if ( re.search("\.cf$",cnf_file) ):
      exec(compile(open(cnf_file).read(), cnf_file, 'exec'))
  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["conf"])
ac_abinit_outs = cnf.get("ac_output","output_files").split()
ac_abinit_cmds = dict()
for cmd in cnf.options("ac_commands"):
  ac_abinit_cmds[cmd] = cnf.get("ac_commands",cmd)
try:
  ac_abinit_dirs = cnf.get("ac_output","subdirs").split()
except:
  ac_abinit_dirs = list()

# Add subsystems
cnf_subs = MyConfigParser()
cnf_subs.read(my_configs["bsys"])
ac_abinit_dirs += sorted([item for item in cnf_subs.sections() \
  if (cnf_subs.get(item, "mode") == "detached") and (cnf_subs.get(item, "type") == "data")])


# Start writing macro
m4 = open(my_output, "wt")
m4.write(macro_header(my_name,now))

# List non-Makefile config files
lst = ""
for out in ac_abinit_outs:
  lst += "    %s\n" % (out)

# List specific Makefiles
lst += "    Makefile\n"
for add in ac_abinit_dirs:
  lst += "    %s/Makefile\n" % (add)

# Process core libraries
cnf = MyConfigParser()
cnf.read(my_configs["libs"])
abinit_corelibs = cnf.sections()
abinit_corelibs.sort()
for lib in abinit_corelibs:
  if ( cnf.get(lib, "parent") == "common" ):
    par_dir = "shared/common/src/%s" % lib
  elif ( cnf.get(lib, "parent") == "libpaw" ):
    par_dir = "shared/libpaw/src"
  else:
    par_dir = "src/%s" % lib
  lst += "    %s/Makefile\n" % (par_dir)

# Add binaries
lst += "    src/98_main/Makefile\n"

# Write list
m4.write(lst+" ])\n\n  dnl Commands\n")

# Write commands
for cmd in ac_abinit_cmds:
  m4.write("  AC_CONFIG_COMMANDS([%s],[%s])\n" % (cmd,ac_abinit_cmds[cmd]))

# The end
m4.write(macro_footer())
m4.close()

tmp = getoutput("./config/scripts/add-header-typed Autoconf %s" % (my_output))
if ( tmp != "" ):
  print(tmp)
