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

#
# NOTES:
#
#   * This script changes the current directory to doc/.
#   * The structure of the script is ready for individual builds.
#

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
#

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 = ["doc/config/specs/documents.conf"]

# 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 the 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)
    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_docs = cnf.sections()

# First go to the doc subdirectory
os.chdir("doc")

# Prepare regexps
olddir = re.compile(",.*")
tmpdir = re.compile("tmp-*")
vimswp = re.compile("\..*\.swp")

# Init dirs & files that should not be distributed
nodist_dirs  = ["autom4te.cache"]
nodist_files = [
  "AUTHORS","COPYING","ChangeLog","INSTALL","NEWS",
  "aclocal.m4","configure","configure.ac",
  "autogen.sh","wipeout.sh",
  "Makefile.am","Makefile.in","Makefile"]

# Init dirs & files that should not be installed
noinst_dirs  = list()
noinst_files = list()

# Get list of subdirectories
doc_subdirs = list()
for tmp in os.listdir("."):
  if ( os.path.isdir("%s" % (tmp)) ):
    doc_subdirs.append(tmp)
doc_subdirs.sort()

# Init file list
doc = "nobase_dist_doc_DATA ="
ext = ""

# Explore current directory
for dat in os.listdir("."):
  if ( os.path.isfile(dat) and (not os.path.islink(dat)) and \
       (not dat in nodist_files) and (not vimswp.match(dat))  ):
    if (dat in noinst_files ):
      ext += " \\\n\t%s" % (dat)
    else:
      doc += " \\\n\t%s" % (dat)

# Explore subdirectories
for sub in doc_subdirs:

  # Get list of ignored files
  if ( cnf.has_option(sub,"ignore") ):
    ign_list = cnf.get(sub,"ignore").split()
  else:
    ign_list = list()

  if ( (not sub in nodist_dirs) and (not sub in noinst_dirs) ):
    for root,dirs,files in os.walk(sub):
      # Clean-up lists
      if ( "Makefile.am" in files ):
        files.remove("Makefile.am")
      if ( "Makefile.in" in files ):
        files.remove("Makefile.in")
      if ( "Makefile" in files ):
        files.remove("Makefile")

      # We don't want to distribute nor install temporary directories
      tmp_dirs = [item for item in dirs if ( olddir.match(item) or \
        tmpdir.match(item) or (item in ign_list) )]
      for item in tmp_dirs:
        dirs.remove(item)

      # Get rid of ignored files
      files = [item for item in files if ( not item in ign_list )]
      files.sort()

      # Add data files
      for dat in files:
        if ( not vimswp.match(dat) ):
          if ( dat in noinst_files ):
            ext += " \\\n\t%s" % (os.path.join(root,dat))
          else:
            doc += " \\\n\t%s" % (os.path.join(root,dat))

  elif ( not sub in nodist_dirs ):
    ext += " \\\n\t%s" % (sub)

# Final adjustments
doc += "\n"
if ( ext != "" ):
  ext = "EXTRA_DIST =" + ext + "\n"

# Go back to top directory
os.chdir("..")

# Create top doc makefile
mf = file("doc/Makefile.am","w")
mf.write(makefile_header(my_name,now))
mf.write(doc)
if ( ext != "" ):
  mf.write("\n"+ext)
#mf.write("""
#dist-hook:
#	rm -f $(distdir)/AUTHORS
#	rm -f $(distdir)/ChangeLog
#	rm -f $(distdir)/COPYING
#	rm -f $(distdir)/INSTALL
#	rm -f $(distdir)/NEWS
#""")

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