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

ACLOCAL_AMFLAGS = -I config/m4

""" % (name,stamp,name)



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

#
# Main program
#

# Initial setup
my_name    = "make-makefiles-top"
my_configs = ["config/specs/autotools.conf"]

sep = "# ---------------------------------------------------------------------------- #\n\n"

# 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)
cnf = MyConfigParser()
for cnf_file in my_configs:
  if ( not os.path.exists(cnf_file) ):
    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.read(my_configs[0])
abinit_other_dirs = cnf.get("am_dist","extra_dirs").split()
abinit_top_subdirs = cnf.get("am_dist","top_subdirs")

clean = "CLEANFILES = abilint.out abilint.log config.optim\n\n"

ext = "EXTRA_DIST ="
for dir in abinit_other_dirs:
  ext += "\n"+commands.getoutput("find %s -type f -a ! -name '.*.swp' 2> /dev/null" % (dir))
ext  = re.sub("\n"," \\\n\t",ext)
ext += "\n\n"

# Write Makefile.am
mf = file("Makefile.am","w")
mf.write(makefile_header(my_name,now))
mf.write("SUBDIRS = %s\n\n" % (abinit_top_subdirs))
mf.write(clean)
mf.write(ext)
add = "config/makefiles/top.am"
if ( os.path.exists(add) ):
  mf.write(sep+file(add,"r").read())
mf.close()
