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

try:
    from configparser import ConfigParser,NoOptionError
except ImportError:
    from ConfigParser import ConfigParser,NoOptionError
from time import gmtime,strftime

import subprocess
import os
import re
import sys

class MyConfigParser(ConfigParser):

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

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

#
# Subroutines
#

# Init macro header
def macro_info(name,stamp,fbk_list):

  # Create template
  ret = """# Generated by %s on %s

#
# Display information about fallbacks status
#

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



# AFB_INFO_DISPLAY()
# ------------------
#
# Reports about the current fallbacks configuration.
#
AC_DEFUN([AFB_INFO_DISPLAY],[
  # Init
  if test "${enable_hdf5}" = "yes"; then
    tmp_s_hdf5=`echo "${afb_hdf5_ok}" | sed -e 's/^yes/enabled/;s/^no/disabled/'`
  else
    tmp_s_hdf5="disabled"
  fi
@FBK_FORMAT@
  # Display configuration
  cat <<EOF

Abinit Fallbacks configuration
==============================

Global parameters
-----------------

  * tarball repository : ${abinit_tardir}
  * install prefix     : ${prefix}

Fallbacks status
----------------

The following summary table indicates the status of the fallbacks, whether
they will be installed, if their build parameters have been customized
through environment variables, and whether tricks have been internally
applied to their build parameters.

@FBK_STATUS@

Full information about the current configuration can be found in the
fallbacks.dump file.

Configuration complete.
You may now type "make" to build the Abinit Fallbacks.
Note: "make -j<n>" may or may not work, depending on the design of the
individual packages. Please contact their upstream developers directly
for any issue related to parallel builds.

EOF
]) # AFB_INFO_DISPLAY
""" % (name,stamp,name)

  # Report status of each package
  fbk_form  = ""
  fbk_stat  = "  +----------------+--------+--------+--------+--------+\n"
  fbk_stat += "  |Fallback        |Status  |Install |Custom  |Tricks  |\n"
  fbk_stat += "  +----------------+--------+--------+--------+--------+\n"
  for pkg in fbk_list:
    fbk_form += "  tmp_s_%s=`echo \"${afb_%s_ok}\" | sed -e 's/^yes/ok/;s/^no/broken/' | awk '{printf(\"%%-8s\",[$]1);}'`\n" % (pkg,pkg)
    fbk_form += "  tmp_i_%s=`echo \"${enable_%s}\" | awk '{printf(\"%%-8s\",[$]1);}'`\n" % (pkg,pkg)
    fbk_form += "  tmp_c_%s=`echo \"${afb_%s_custom}\" | awk '{printf(\"%%-8s\",[$]1);}'`\n" % (pkg,pkg)
    fbk_form += "  tmp_t_%s=`echo \"${afb_%s_tricks}\" | awk '{printf(\"%%-8s\",[$]1);}'`\n" % (pkg,pkg)
    fbk_stat += "  |%-16s|${tmp_s_%s}|${tmp_i_%s}|${tmp_c_%s}|${tmp_t_%s}|\n" % \
      (pkg,pkg,pkg,pkg,pkg)
  fbk_stat += "  +----------------+--------+--------+--------+--------+"

  # Substitute macro
  ret = re.sub("@FBK_FORMAT@",fbk_form,ret)
  ret = re.sub("@FBK_STATUS@",fbk_stat,ret)

  return ret



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

#
# Main program
#

# Initial setup
my_name    = "make-macros-info"
my_configs = ["config/specs/fallbacks.conf"]
my_output  = "config/m4/auto-info.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("config/specs/fallbacks.conf") ):
  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 open(s)
for cnf_file in my_configs:
  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[0])
abinit_fallbacks = cnf.sections()
abinit_fallbacks.sort()

# Write down macro
open(my_output,"w").write(macro_info(my_name,now,abinit_fallbacks))
