#!/usr/bin/env python
#
# Copyright (C) 2014-2016 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 ConfigParser import ConfigParser
from time import gmtime,strftime

import os
import re
import sys

class MyConfigParser(ConfigParser):

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

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

#
# M4 macro template
#

def m4_template(name,stamp):

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

#
# Macro to fix the include flags of ABINIT
#

#
# 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_INCFLAGS_CORRECT()
# ----------------------
#
# Corrects the include flags so that /usr/include is always forced last.
# This trick works around an issue causing failing builds when compiled
# Fortran modules are incompatible with the current compiler (e.g. when
# a new version of gfortran is released).
#
AC_DEFUN([ABI_INCFLAGS_CORRECT],[
  abi_extra_incs=""
  AC_MSG_NOTICE([correcting include flags])

@INCS@  unset tmp_incs

  AC_SUBST(abi_extra_incs)
]) # ABI_INCFLAGS_CORRECT
""" % (name,stamp,name)

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

#
# Main program
#

# Initial setup
my_name    = "make-macros-incflags"
my_output  = "config/m4/auto-incflags.m4"
my_configs = {
  "libs":"config/specs/corelibs.conf",
  "bins":"config/specs/binaries.conf"}

# 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") ):
  sys.stderr.write("%s: You must be in the top of an ABINIT source tree.\n" % my_name)
  sys.stderr.write("%s: Aborting now.\n" % my_name)
  sys.exit(1)

# Check config file(s)
for cfg_file in my_configs.values():
  if ( not os.path.exists(cfg_file) ):
    sys.stderr.write("%s: Could not find config file (%s).\n" % (my_name,cfg_file))
    sys.stderr.write("%s: Aborting now.\n" % 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["libs"])
deps = []
for lib in cnf.sections():
  if ( cnf.has_option(lib, "dependencies") ):
    deps += cnf.get(lib, "dependencies").split()
cnf = MyConfigParser()
cnf.read(my_configs["bins"])
for prg in cnf.sections():
  if ( cnf.has_option(prg, "dependencies") ):
    deps += cnf.get(prg, "dependencies").split()
deps = list(set(deps))
deps.sort()

# Remove specific paths from include flags
m4_incs = ""
for dep in deps:
  m4_incs += "  AC_MSG_CHECKING([whether to postpone -I/usr/include for %s])\n" % dep 
  m4_incs += "  tmp_incs=`echo \"${lib_%s_incs}\" | grep -- '-I/usr/include[ $]'`\n"
  m4_incs += """\
  if test "${tmp_incs}" = ""; then
    AC_MSG_RESULT([no])
  else
    AC_MSG_RESULT([yes])
    abi_extra_incs="-I/usr/include"
    lib_%s_incs=`echo "${lib_%s_incs}" | sed -e 's,-I/usr/include[ $],,'`
  fi\n""" % (dep,dep)

# Write M4 macro
file(my_output,"w").write(re.sub("@INCS@",m4_incs,m4_template(my_name,now)))
