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

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

#
# Main program
#

# Initial setup
my_name   = "update-options-conf"
my_config = "config/specs/options.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 an ABINIT source tree." % my_name
  print "%s: Aborting now." % my_name
  sys.exit(1)

# Check config file(s)
if ( not os.path.exists(my_config) ):
  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
re_sta = re.compile("^status.*(changed|new|removed|renamed)")
re_sec = re.compile("^\\[.*\\]$")
cnf = MyConfigParser()
cnf.read(my_config)
opt_inp = file(my_config,"r").readlines()
opt_out = ""

# Process config file
sec_buf = ""
sec_del = False
sec_idx = 0
sec_sta = ""
sec_tit = ""
for i in range(0,len(opt_inp)):
  line = opt_inp[i]

  # Starting a new section
  if ( re_sec.match(line) ):
    if ( not sec_del ):
      opt_out += sec_buf
    sec_buf = ""
    sec_del = False
    sec_idx = i
    sec_tit = re.sub("[\\[\\]]","",line).strip()

    if ( sec_tit != "DEFAULT" ):
      sec_sta = cnf.get(sec_tit,"status")
      if ( sec_sta == "removed" ):
        sec_del = True

  # Delete all status lines, but obsolete and unchanged
  if ( not re_sta.match(line) ):
    sec_buf += line

# Rewrite config file
file(my_config,"w").write(opt_out)
