#!/usr/bin/env python
#
# Copyright (c) 2005-2007 The ABINIT Group (Yann Pouillon)
# All rights reserved.
#
# 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 time import gmtime,strftime

import commands
import os
import re
import sys

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

#
# Subroutines
#

# Macro header
def macro_header(name,stamp):

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



# ABI_OUTPUT()
# ------------
#
# Outputs configuration for ABINIT.
#
AC_DEFUN([ABI_OUTPUT],
[dnl Config files
 AC_CONFIG_FILES([config.mk config.sh
""" % (name,stamp,name)



# Macro footer
def macro_footer():

 return """
 dnl Output everything
 AC_OUTPUT
]) # ABI_OUTPUT
"""



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

#
# Main program
#

# Initial setup
my_name    = "make-macros-output"
my_configs = ["config/specs/libraries.cf","config/specs/autoconf.cf"]
my_output  = "config/m4/do-not-edit-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("src/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)
for cnf in my_configs:
 if ( os.path.exists(cnf) ):
  execfile(cnf)
 else:
  print "%s: Could not find config file (%s)." % (my_name,cnf)
  print "%s: Aborting now." % my_name
  sys.exit(2)

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

# Start writing macro
m4 = file(my_output,"w")
m4.write(macro_header(my_name,now))

# List non-Makefile config files
lst = ""
for out in ac_abinit_outs:
 lst += "    %s\n" % (out)

# List Makefiles
lst += "    Makefile\n    lib/Makefile\n    src/Makefile\n"

# Process each library
for lib in abinit_libs:

 # Init
 if ( lib in abilibs_specs ):
  specs = abilibs_specs[lib]
 else:
  specs = ABI_LIB_NIL

 if ( (specs & ABI_LIB_EXT) == 0 ):
  lib_dir = "src"
 else:
  lib_dir = "lib"

 # Add library Makefile to list
 lst += "    %s/%s/Makefile\n" % (lib_dir,lib)

lst += "    src/main/Makefile\n"

# List additional Makefiles
for add in ac_abinit_dirs:
 lst += "    %s/Makefile\n" % (add)

# Write list
m4.write(lst+" ])\n\n dnl Commands\n")

# Write commands
for cmd in ac_abinit_cmds:
 m4.write(" AC_CONFIG_COMMANDS([%s],[%s])\n" % (cmd,ac_abinit_cmds[cmd]))

# The end
m4.write(macro_footer())
m4.close()

tmp = commands.getoutput("./config/scripts/add-header-typed Autoconf %s" % (my_output))
if ( tmp != "" ):
 print tmp
