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

# Macro header
def macro_template(name,stamp):

  return """\
# -*- M4 -*-
#
# Copyright (C) 2013-2017 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.
#

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



# ABIDOC_OUTPUT()
# ---------------
#
# Outputs configuration for ABINIT.
#
AC_DEFUN([ABIDOC_OUTPUT],[
  dnl Config files
  AC_CONFIG_FILES([@MAKEFILES@])

  AC_OUTPUT
]) # ABIDOC_OUTPUT
""" % (name,stamp,name)



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

#
# Main program
#

# Initial setup
my_name   = "make-macros-output"
my_config = "config/specs/documents.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("build/config-template.ac") ):
  print("%s: You must be in the top of an ABINIT documentation source tree." % my_name)
  print("%s: Aborting now." % my_name)
  sys.exit(1)

# Read config file(s)
if ( not os.path.exists(my_config) ):
    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
cnf = MyConfigParser()
cnf.read(my_config)

# Init
m4  = macro_template(my_name,now)
lst = "\n    Makefile"

# Process directories
subdirs = cnf.sections()
subdirs.sort()
for sub in subdirs:
  lst += "\n    %s/Makefile" % (sub)

# Save macro
m4 = re.sub("@MAKEFILES@",lst,m4)
open(my_output, "wt").write(m4)
