#!/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
#

# Makefile header
def makefile_header(name,stamp):

 return """#
# Makefile for ABINIT                                      -*- Automake -*-
# Generated by %s on %s

#
# IMPORTANT NOTE
#
# Any manual change to this file will systematically be overwritten.
# Please modify the %s script or its config file instead.
#

AM_CPPFLAGS = @CPPFLAGS_OPT@
AM_FCFLAGS  = @FCFLAGS_FREEFORM@ @fcflags_opt_main@
AM_LDFLAGS  = @FC_LDFLAGS@

abiexecdir = @abinit_bindir@

""" % (name,stamp,name)



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

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-binaries"
my_configs = ["config/specs/libraries.cf","config/specs/binaries.cf"]
my_output  = "src/main/Makefile.am"

# 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())

# Generate library and include lists
lib_list = ""
inc_list = ""

for lib in abinit_libs:
 if ( lib in abilibs_specs ):
  lib_specs = abilibs_specs[lib]
 else:
  lib_specs = ABI_LIB_NIL

 if ( (lib_specs & ABI_LIB_EXT) == 0 ):
  if ( (lib_specs & ABI_LIB_MPI) == 0 ):
   lib_list += "LIB_%s = $(top_builddir)/src/%s/lib%s.a\n" % \
    (re.sub("^[0-9]","",lib).upper(),lib,lib)
  else:
   lib_list += "LIB_%sS = $(top_builddir)/src/%s/lib%ss.a\n" % \
    (re.sub("^[0-9]","",lib).upper(),lib,lib)
   lib_list += "LIB_%sP = $(top_builddir)/src/%s/lib%sp.a\n" % \
    (re.sub("^[0-9]","",lib).upper(),lib,lib)

  # Add include
  if ( (lib_specs & ABI_LIB_INC) != 0 ):
   inc_list += " -I../%s" % (lib)
 else:
  if ( (lib_specs & ABI_LIB_MPI) == 0 ):
   if ( (lib_specs & ABI_LIB_OPT) == 0 ):
    lib_list += "LIB_%s = -L$(top_builddir)/lib/%s -l%s\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib,lib)
   else:
    lib_list += "LIB_%s = @%s_ldflags@\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib)
  else:
   if ( (lib_specs & ABI_LIB_OPT) == 0 ):
    lib_list += "LIB_%sS = -L$(top_builddir)/lib/%s -l%ss\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib,lib)
    lib_list += "LIB_%sP = -L$(top_builddir)/lib/%s -l%sp\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib,lib)
   else:
    lib_list += "LIB_%sS = @%ss_ldflags@\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib,lib)
    lib_list += "LIB_%sP = @%sp_ldflags@\n" % \
     (re.sub("^[0-9]","",lib).upper(),lib,lib)

  # Add include
  if ( (lib_specs & ABI_LIB_INC) != 0 ):
   inc_list += " @%s_include@" % (lib)

lib_list += "\n"

# Generate binary list
bin_list = "abiexec_PROGRAMS ="
mpi_list = "if DO_BUILD_PARALLEL\n abiexec_PROGRAMS +="
add_list = ""
cln_list = "CLEANFILES ="

for bin in abinit_bins:

 # Init
 if ( bin in abibins_specs ):
  specs = abibins_specs[bin]
 else:
  specs = ABI_BIN_NIL


 if ( (specs & ABI_BIN_ADD) == 0 ):
  cln_list += " \\\n\t%s_cpp.f90" % (bin)
  if ( not os.path.exists("src/main/%s.F90" % (bin)) ):
   sys.stderr.write("Error: No such file or directory: 'src/main/%s.F90'\n" % \
    (bin))
   sys.exit(4)

 if ( specs == ABI_BIN_NIL ):
  bin_list += " \\\n\t%s" % (bin)
 else:
  if ( (specs & ABI_BIN_MPI) != 0 ):
   bin_list += " \\\n\t%s" % re.sub(".$","s",bin)
   mpi_list += " \\\n\t%s" % re.sub(".$","p",bin)
  if ( (specs & ABI_BIN_ADD) != 0 ):
   add_specs = abibins_add_specs[bin]
   if ( add_specs[2] == "" ):
    bin_list += " \\\n\t%s" % (bin)
   else:
    add_list += "if %s\n abiexec_PROGRAMS += %s\nendif\n" % (add_specs[2],bin)

cln_list += "\n"
bin_list += "\n\n"
mpi_list += "\nendif\n\n"
if ( add_list != "" ):
 add_list += "\n"

# Start writing to Makefile.am
mf = file(my_output,"w")
mf.write(makefile_header(my_name,now))
mf.write("INCLUDES = %s\n\n" % (inc_list))
mf.write("# Internal libraries\n"+lib_list)
mf.write("# Binary list\n"+bin_list+mpi_list+add_list)

# Process each binary
for abibin in abinit_bins:

 # Init
 if ( abibin in abibins_specs ):
  specs = abibins_specs[abibin]
 else:
  specs = ABI_BIN_NIL

 if ( (specs & ABI_BIN_MPI) == 0 ):
  bins = [abibin]
 else:
  bins = [re.sub(".$","s",abibin),re.sub(".$","p",abibin)]

 if ( (specs & ABI_BIN_ADD) == 0 ):
  abisrc = abibin
  abicpp = ""
  abicnd = ""
 else:
  (abisrc,abicpp,abicnd) = abibins_add_specs[abibin]

 # Produce all binaries related to one source file
 for bin in bins:

  # Init
  bin_cppflags = abicpp
  bin_libs = ""
  bin_ldflags = ""

  # Check all libraries the binary depends on
  for lib in eval("%s_deps" % (abibin)):

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

   # Set suffix for library
   if ( (lib_specs & ABI_LIB_MPI) == 0 ):
    lib_suffix = ""
   else:
    if ( (specs & ABI_BIN_MPI) == 0 ):
     lib_suffix = "s"
    else:
     if ( bin == bins[0] ):
      lib_suffix = "s"
     else:
      lib_suffix = "p"

   bin_libs += " \\\n\t$(LIB_%s%s)" % (re.sub("^[0-9]","",lib).upper(),lib_suffix.upper())

  # Check whether we are considering a parallel binary
  if ( ((specs & ABI_BIN_MPI) != 0) and (bin == bins[1]) ):
   bin_ldflags += " \\\n\t$(MPI_FC_LDFLAGS)"
  bin_ldflags += " \\\n\t$(FCLIBS)\n"

  # Write results
  indent = ""
  mf.write("# %s.F90 ---> %s\n" % (abisrc,bin))

  # Parallel version
  if ( ((specs & ABI_BIN_MPI) != 0) and (bin == bins[1]) ):
   mf.write("if DO_BUILD_PARALLEL\n")
   indent = " "

  # Additional binary
  if ( abicnd != "" ):
   mf.write("if %s\n" % (abicnd))
   indent = " "

  # Binary sources
  mf.write("%s%s_SOURCES = %s.F90\n" % (indent,bin,abisrc))

  # Parallel binary flags
  if ( ((specs & ABI_BIN_MPI) != 0) and (bin == bins[1]) ):
   mf.write("%s%s_CPPFLAGS = @MPI_CPPFLAGS@\n" % \
    (indent,bin))
   mf.write("%s%s_FCFLAGS = @FCFLAGS_FREEFORM@ @MPI_FCFLAGS@\n" % \
    (indent,bin))

  # Additional binary flags
  if ( bin_cppflags != "" ):
   mf.write("%s%s_CPPFLAGS = @CPPFLAGS@ %s\n" % (indent,bin,bin_cppflags))

  # LDFLAGS
  mf.write("%s%s_LDADD =%s%s" % (indent,bin,bin_libs,bin_ldflags))

  # Close conditionals
  if ( (((specs & ABI_BIN_MPI) != 0) and (bin == bins[1])) or (abicnd != "") ):
   mf.write("endif\n\n")
  else:
   mf.write("\n")

# Write list of files to clean
mf.write(cln_list)

# Write additional hand-made information
add = "src/main/abinit.amf"
if ( os.path.exists(add) ):
 mf.write("\n"+file(add,"r").read())

mf.close()
