#!/usr/bin/env python
#
# Copyright (C) 2005-2012 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 commands
import os
import re
import sys

class MyConfigParser(ConfigParser):

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

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

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

CC = @cc_for_timeout@

bin_PROGRAMS = timeout

timeout_SOURCES = timeout.c
timeout_CFLAGS = -O0

""" % (name,stamp,name)



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

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-nightly"
my_configs = ["config/specs/binaries.conf"]
my_output  = "tests/Nightly/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/98_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_file in my_configs:
  if ( os.path.exists(cnf_file) ):
    if ( re.search("\.cf$",cnf_file) ):
      execfile(cnf_file)
  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])

# Write Makefile.am core
mf = file(my_output,"w")
mf.write(makefile_header(my_name,now))

# Init extra file list
ext = ""

# Include additional hand-made information
add = "tests/Nightly/abinit.amf"
if ( os.path.exists(add) ):
  ext += " \\\n\tabinit.amf"

# Include RoboDOC header
hdr = "tests/Nightly/_Nightly_"
if ( os.path.exists(hdr) ):
  ext += " \\\n\t_Nightly_"

# Write list of extra files
if ( ext != "" ):
  mf.write("EXTRA_DIST ="+ext+"\n")

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

mf.close()
