
import subprocess as sp
import os
import sys

base_dict = {
    'PROJECT': 'kitsap_run84',
    'SMOOTH':0.1,
    'ALPHA': 6,
    'BETA': 10,
    'GAMMA': 0.5, 
    'MU': 2.4,
    'DA': 0.2,
    'DB': 0.4,
    'DMIN': 0.5,
    'UA': 0.9,
    'UB': 0.21,
    'UMIN':0.5
}

#var_dict={"PROJECT": ['kitsap_run84_pnnl']}
var_dict={"PROJECT": [
    'access1.0_RCP85_WRF_run84_1969-2099',
    'access1.3_RCP85_WRF_run84_1969-2099',
    'bcc-csm1.1_RCP85_WRF_run84_1969-2099',
    'canesm2_RCP85_WRF_run84_1969-2099',
    'ccsm4_RCP85_WRF_run84_1969-2099',
    'csiro-mk3.6.0_RCP85_WRF_run84_1969-2099',
    'fgoals-g2_RCP85_WRF_run84_1969-2099',
    'gfdl-cm3_RCP85_WRF_run84_1969-2099',
    'giss-e2-h_RCP85_WRF_run84_1969-2099',
    'miroc5_RCP85_WRF_run84_1969-2099',
    'mri-cgcm3_RCP85_WRF_run84_1969-2099',
    'noresm1-m_RCP85_WRF_run84_1969-2099'
]}
var_dict={"PROJECT": [
    'access1.0_RCP85',
    'access1.3_RCP85',
    'bcc-csm1.1_RCP85',
    'canesm2_RCP85',
    'ccsm4_RCP85',
    'csiro-mk3.6.0_RCP85',
    'fgoals-g2_RCP85',
    'gfdl-cm3_RCP85',
    'giss-e2-h_RCP85',
    'miroc5_RCP85',
    'mri-cgcm3_RCP85',
    'noresm1-m_RCP85'
]}

var_dict={"PROJECT": ['access1.0_RCP45']}

def file_chmod(infile, mode='664'):
    '''Changes file privileges with default of -rw-rw-r--. Convert mode from
    string to base-8  to be compatible with python 2 and python 3.'''
    os.chmod(infile, int(mode, 8))


def replace_var_pythonic_config(src, dst, header=None, **kwargs):
    ''' Python style ASCII configuration file from src to dst. Dost not remove
    comments or empty lines. Replace keywords in brackets with variable values
    in **kwargs dict. '''
    with open(src, 'r') as fsrc:
        with open(dst, 'w') as fdst:
            lines = fsrc.readlines()
            if header is not None:
                fdst.write(header)
            for line in lines:
                line = line.format(**kwargs)
                fdst.write(line)
    file_chmod(dst)

sdir = "/home/disk/rocinante/DATA/temp/chico/hyak/scripts/"
ftmp = "{}/config/rbm.template".format(sdir)
fcfg = "{}/config/rbm.cfg".format(sdir)
exe = "{}/run_dhsvm-rbm.bsh".format(sdir)
    
for key in var_dict:
    print('key: ', key)
    print('var-key:', var_dict[key])
    kwargs = base_dict.copy()

    for x in var_dict[key]:
        print(x)

        if key == 'PROJECT':
            #kwargs[key] = base_dict[key] + '_' + x
            kwargs[key] = x
            scen = "{}".format(x)
            kwargs['SCEN'] = scen
            
        else:
            kwargs[key] = x
            scen = "{}-{}".format(key, x)
            kwargs['SCEN'] = scen

        print('kwarg:', kwargs[key])
        print('scen: ', scen)
        
        replace_var_pythonic_config(ftmp, fcfg, header=None, **kwargs)
        print(fcfg)
        sp.run([exe, fcfg])
