#!/usr/bin/env python
import os,re,subprocess
import damask

damaskEnv = damask.Environment('../')          # script location relative to root
baseDir = damaskEnv.relPath('code/')

# changing dirs and compiler in makefile
compiler ={True:'ifort',False:'gfortran'}[\
           subprocess.call(['which', 'ifort'],\
           stdout=subprocess.PIPE, stderr=subprocess.PIPE) == 0]
makefile = open(os.path.join(baseDir,'Makefile'))
content = makefile.readlines()
makefile.close()
makefile = open(os.path.join(baseDir,'Makefile'),'w')
for line in content:
  m = re.match(r'(FFTW|IMKL|ACML|LAPACK)ROOT\s*\?=\s*',line)
  c = re.match(r'F90\s*\?=\s*',line)
  if m:
    if m.group(1).lower() in damaskEnv.pathInfo:
      substitution = damaskEnv.pathInfo[m.group(1).lower()]
    else:
      substitution = ''
    line = '%sROOT ?= %s\n'%(m.group(1),substitution)
  if c:
    line = 'F90 ?= %s\n'%compiler
  makefile.write(line)
makefile.close()