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

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

""" % (name,stamp,name)



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

#
# Main program
#

# Script name
my_name    = "make-makefiles-doc"
my_configs = ["config/specs/documents.cf"]

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

# Init lists
doc = "install-data-local:\n\t$(INSTALL) -d -m 755 $(DESTDIR)$(abinit_docdir)"
ext = "EXTRA_DIST ="

# Write one Makefile per subdirectory
for root,dirs,files in os.walk("doc"):
 # Clean-up lists
 if ( "Makefile.am" in files ):
  files.remove("Makefile.am")
 if ( "Makefile.in" in files ):
  files.remove("Makefile.in")

 # Relative root
 rel = re.sub("^doc","",root)

 # Install subdirectories
 for sub in dirs:
  doc += "\n\t$(INSTALL) -d -m 755 $(DESTDIR)$(abinit_docdir)%s/%s" % \
   (rel,sub)

 # Install data files
 for dat in files:
  doc += "\n\t$(INSTALL_DATA) '$(srcdir)%s/%s' " % (rel,dat) \
      +  "'$(DESTDIR)$(abinit_docdir)%s'" % (rel)
  ext += " \\\n\t%s/%s" % (re.sub("^doc",".",root),dat)

doc += "\n"
ext += "\n"

# Write makefile
mf = file("doc/Makefile.am","w")
mf.write(makefile_header(my_name,now))
mf.write(doc)
mf.write("\n"+ext)

# Write additional data
add= "config/makefiles/doc.am"
if( os.path.exists(add) ):
 mf.write("\n"+file(add,"r").read())

# End of file
mf.close()
