#! /usr/bin/env python

import os
import re
import sys

rootRe = re.compile("Kokkos(.*?)_eti_spec_(.*?)[.]hpp")
cppReplRe = re.compile("namespace Impl {\n(.*)", re.DOTALL)

def walker(topdir, dirname, files):
  os.chdir(dirname)
  for f in files:
    if f == "change":
      continue
    match = rootRe.search(f)
    if not match:
      sys.exit("Bad file %s" % f)
    fxn, typ = match.groups()
    if f.endswith("hpp"):
      newPath = f + ".in"
      typ = typ.upper()
      text = open(f).read()
      repl = "namespace Impl {\n@%s_ETI_%s_BLOCK@\n  } //IMPL \n} //Kokkos\n#endif" % (fxn.upper(), typ)
      newText = cppReplRe.sub(repl, text)
      print newText
      cmd = "git mv %s %s" % (f, newPath)
      print("%s : %s" % (os.getcwd(), cmd))
      os.system(cmd)
      open(newPath, "w").write(newText)
  os.chdir(topdir)

os.path.walk(".", walker, os.getcwd())

