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

#
# Environment variables relevant to ABINIT
#

#
# IMPORTANT NOTE
#
# This file has been automatically generated by the %s
# script. Any change will systematically be overwritten.
#
""" % (name,stamp,name)



# Autoconf macro template
def abi_macro_autoconf():

 return """


# ABI_ENV_AC_UPDATE(LANG)
# -----------------------
#
# Updates Autoconf build environment.
#
AC_DEFUN([ABI_ENV_AC_UPDATE],
[dnl Please note that the existing environment will always be overwritten.
 dnl Thus you should save sensistive data before calling this macro.

 dnl Check arguments
 m4_if([$1], [tmp_lang="$1"], [tmp_lang="Fortran"])dnl

 dnl Update linker flags
 case "$1" in
  C)
   LDFLAGS="${CC_LDFLAGS}"
   ;;
  C++)
   LDFLAGS="${CXX_LDFLAGS}"
   ;;
  Fortran)
   LDFLAGS="${FC_LDFLAGS}"
   ;;
 esac

 dnl Update linker additional libs
 LIBS="${CC_LIBS}"
 CXXLIBS="${CXX_LIBS}"
 FCLIBS="${FC_LIBS}"

 unset tmp_lang
]) # ABI_ENV_AC_UPDATE
"""



# Define macro template
def abi_macro_define():

 return """


# ABI_ENV_DEFINE()
# ----------------
#
# Declares ABINIT environment variables and resets the internal
# variables. This is necessary if we want to have external variables
# overriding the contents of the config files.
#
AC_DEFUN([ABI_ENV_DEFINE],
[
@MACRO@
]) # ABI_ENV_DEFINE
"""



# Init macro template
def abi_macro_init():

 return """


# ABI_ENV_INIT()
# --------------
#
# Sets ABINIT environment variables to their default values.
#
AC_DEFUN([ABI_ENV_INIT],
[
@MACRO@
]) # ABI_ENV_INIT
"""



# Backup macro template
def abi_macro_backup():

 return """


# ABI_ENV_BACKUP()
# ----------------
#
# Saves all ABINIT environment variables.
#
AC_DEFUN([ABI_ENV_BACKUP],
[dnl All variables will be saved, yet please note that they may be
 dnl conditionally restored (see ABI_ENV_RECALL for details).
@MACRO@
]) # ABI_ENV_BACKUP
"""



# Recall macro template
def abi_macro_recall():

 return """


# ABI_ENV_RECALL()
# ----------------
#
# Restores all previously-saved non-empty ABINIT environment variables.
#
AC_DEFUN([ABI_ENV_RECALL],
[dnl The following ensures that non-empty environment variables always override
 dnl what is read from the config files.
@MACRO@
]) # ABI_ENV_RECALL
"""



# Restore macro template
def abi_macro_restore():

 return """


# ABI_ENV_RESTORE()
# -----------------
#
# Restores all previously-saved ABINIT environment variables.
#
AC_DEFUN([ABI_ENV_RESTORE],
[dnl The following ensures that non-empty environment variables always override
 dnl what is read from the config files.
@MACRO@
]) # ABI_ENV_RESTORE
"""



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

#
# Main program
#

# Initial setup
my_name    = "make-macros-env"
my_configs = ["config/specs/env.cf"]
my_output  = "config/m4/do-not-edit-env.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))

# Write Autoconf macro
m4.write(abi_macro_autoconf())

# Process environment variables for define
src = ""
for var in abinit_env_vars:
 if ( var[2] != None ):
  src += "\n dnl %s\n" % (var[1])
  src += " %s=\"\"\n" % (var[0])
  src += " AC_SUBST(%s)\n" % (var[0])

# Write define macro
m4.write(re.sub("@MACRO@",src,abi_macro_define()))

# Process environment variables for init
src = ""
for var in abinit_env_vars:
 if ( var[2] != None ):
  src += "\n dnl %s\n" % (var[1])
  src += " %s=\"%s\"\n" % (var[0],var[2])

# Write init macro
m4.write(re.sub("@MACRO@",src,abi_macro_init()))

# Process environment variables for backup
src = ""
for var in abinit_env_vars:
 src += "\n dnl Save %s\n" % (var[1])
 src += " abi_env_%s=\"${%s}\"\n" % (var[0],var[0])

# Write backup macro
m4.write(re.sub("@MACRO@",src,abi_macro_backup()))

# Process environment variables for recall
src = ""
for var in abinit_env_vars:
 src += "\n dnl Recall %s\n" % (var[1])
 src += " test \"${abi_env_%s}\" != \"\" && \\\n" % (var[0]) \
     +  "  %s=\"${abi_env_%s}\"\n" % (var[0],var[0])

# Write recall macro
m4.write(re.sub("@MACRO@",src,abi_macro_recall()))

# Process environment variables for restore
src = ""
for var in abinit_env_vars:
 src += "\n dnl Restore %s\n" % (var[1])
 src += " %s=\"${abi_env_%s}\"\n" % (var[0],var[0])

# Write restore macro
m4.write(re.sub("@MACRO@",src,abi_macro_restore()))

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

# Write environment dumper (for debugging)
dumper = file("config.dump.in","a")
dumper.write("# Environment variables\n")
for var in abinit_env_vars:
 dumper.write("%s=\"@%s@\"\n" % (var[0],var[0]))
dumper.write("\n")
dumper.close()
