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

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

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

ACLOCAL_AMFLAGS = -I config/m4

AM_DISTCHECK_CONFIGURE_FLAGS = \\
  --without-abinit-common \\
  --without-bigdft \\
  --without-fftw3 \\
  --without-levmar \\
  --without-libpaw \\
  --without-libpsml \\
  --without-libxml2 \\
  --without-papi \\
  --without-pfft \\
  --without-triqs \\
  --without-wannier90 \\
  --without-xmlf90 \\
  @abi_ac_distcheck@ \\
  PYFLAGS="@PYFLAGS@ -B"

""" % (name,stamp,name)



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

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-top"
my_configs = ["config/specs/buildsys.conf"]
my_custom  = "config/dist/custom-modes.lst"

sep = "# ---------------------------------------------------------------------------- #\n\n"

# 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)
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
abinit_subdirs = {"data":{},"subsystem":{}}
abinit_other_dirs = []
abinit_top_dirs = []
cnf.read(my_configs[0])

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

for blk in cnf.sections():
  urgency = cnf.get(blk,"priority")
  sub_list = cnf.get(blk,"subdirs").split()
  sub_type = cnf.get(blk,"type")
  if ( blk in blk_custom ):
    sub_mode = blk_custom[subsys]
  else:
    sub_mode = cnf.get(blk,"mode")
  if ( sub_type == "master" ):
    abinit_other_dirs += cnf.get(blk,"root").split()
    sub_type = "subsystem"
    sub_mode = "attached"
  if ( sub_mode == "attached" ):
    if ( not urgency in abinit_subdirs[sub_type] ):
      abinit_subdirs[sub_type][urgency] = []
    abinit_subdirs[sub_type][urgency] += sub_list
  elif ( sub_mode == "detached" ):
    if ( sub_type == "subsystem" ):
      if ( not urgency in abinit_subdirs["data"] ):
        abinit_subdirs["data"][urgency] = []
      abinit_subdirs["data"][urgency] += sub_list

# Sort subdirs
abinit_priorities = list(abinit_subdirs["data"].keys())
abinit_priorities.sort()
for urgency in abinit_priorities:
  abinit_other_dirs += abinit_subdirs["data"][urgency]
abinit_priorities = list(abinit_subdirs["subsystem"].keys())
abinit_priorities.sort()
for urgency in abinit_priorities:
  abinit_top_dirs += abinit_subdirs["subsystem"][urgency]

# FIXME: hard-coded
clean = "CLEANFILES = config.optim\n\n"

# Generate list of extra files
ext = "EXTRA_DIST =\n"
for subdir in abinit_other_dirs:
  sub_files = "config/dist/auto-%s.lst" % subdir
  ext += open(sub_files, "rt").read()
for xtrafile in os.listdir("./config/dist"):
  if ( re.match("xtra-.*\\.lst", xtrafile) ):
    ext += file(os.path.join("config","dist",xtrafile),"r").read()
ext = re.sub("\n"," \\\n\t",ext[:-1])
ext += "\n\n"
xsubs = sorted([item for item in cnf.sections() \
  if (cnf.get(item, "mode") == "detached") and (cnf.get(item, "type") == "data")])
fbk_tgz = sorted([item for item in os.listdir("./fallbacks") \
        if item.startswith("abinit-fallbacks-") \
        and item.endswith(".tar.gz")])[-1]
ext += "EXTRA_DIST += fallbacks/%s\n\n" % fbk_tgz
ext += "DISTCLEANFILES = fallbacks/Makefile\n\n"

# Write additional cmake information
if ( os.path.exists("CMakeLists.txt") ):
  ext += "EXTRA_DIST += CMakeLists.txt\n"
if ( os.path.exists("config.h.cmake") ):
  ext += "EXTRA_DIST += config.h.cmake\n\n"

# Write Makefile.am
mf = open("Makefile.am", "wt")
mf.write(makefile_header(my_name,now))
mf.write("SUBDIRS = %s\n\n" % (" ".join(abinit_top_dirs + xsubs)))
mf.write(clean)
mf.write(ext)
add = "config/makefiles/top.am"
if ( os.path.exists(add) ):
  mf.write(sep + open(add,"rt").read())
mf.close()
