#!/usr/bin/env python
#
# Copyright (C) 2011-2021 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

import os
import re
import sys

class MyConfigParser(ConfigParser):

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



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

#
# Main program
#

# Initial setup
my_name     = "make-macros-subsystems"
my_config   = "config/specs/buildsys.conf"
my_custom   = "config/dist/custom-modes.lst"
my_macro    = "config/m4/auto-subsystems.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)

# Check if we have a config file
if ( os.path.exists(my_config) ):
  cnf = MyConfigParser()
  cnf.read(my_config)
else:
  print("%s: Could not find config file (%s)." % (my_name,my_config))
  print("%s: Aborting now." % my_name)
  sys.exit(2)

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

# Init macro
m4_macro = """\
# Generated by %s on %s

#
# ABINIT subsystems support 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_SUBSYSTEMS_INIT()
# ---------------------
#
# Defines whether the Abinit subsystems may be built along with the package.
#
AC_DEFUN([ABI_SUBSYSTEMS_INIT],[
  dnl List subsystems
@SUBSYS_PARAMS@
  dnl Configure subdirs
@SUBSYS_CONFIG@
]) # ABI_SUBSYSTEMS_INIT
""" % (my_name,now,my_name)

# Check whether some subsystem modes have been customized
sub_custom = {}
if ( os.path.exists(my_custom) ):
  for line in open(my_custom, "rt").readlines():
    (key,val) = line.strip().split()
    sub_custom[key] = val

# Generate macro data
m4_prms = ""
mf_subdirs = {}
sub_list = cnf.sections()
sub_list.sort()

for subsys in sub_list:
  sub_prty = cnf.get(subsys,"priority")
  sub_type = cnf.get(subsys,"type")
  if ( subsys in sub_custom ):
    sub_mode = sub_custom[subsys]
  else:
    sub_mode = cnf.get(subsys,"mode")

  if ( sub_type == "subsystem" ):
    m4_prms += "  AC_MSG_NOTICE([setting-up %s (type: %s, mode: %s)])\n" % \
      (subsys, sub_type, sub_mode)
    if ( sub_mode == "attached" ):
      if ( not sub_prty in mf_subdirs ):
        mf_subdirs[sub_prty] = []
      mf_subdirs[sub_prty] += cnf.get(subsys,"subdirs").split()

# Build config command
m4_subdirs = ""
priorities = list(mf_subdirs.keys())
priorities.sort()
for prty in priorities:
  m4_subdirs += " " + " ".join(mf_subdirs[prty])
m4_conf = "  AC_CONFIG_SUBDIRS([%s])\n" % m4_subdirs[1:]

# Write down subsystems data
m4_macro = re.sub("@SUBSYS_PARAMS@",m4_prms,m4_macro)
m4_macro = re.sub("@SUBSYS_CONFIG@",m4_conf,m4_macro)
open(my_macro, "wt").write(m4_macro)
