#!/usr/bin/env python3
import os
import sys
import time

USAGE = """
Usage:

    datafilepath <proposal> [<instrument>] [<year>]

set current proposal for an instrument for fit
"""

instrument = os.environ.get('dat_defspec', None)
proposal = os.environ.get('dat_proposal', None)
printit = True

filename = '/tmp/.senv_%s.%s' % (os.environ['USER'], os.getppid())
lines = []
envdict = {}
try:
    with open(filename, 'r') as f:
        for line in f:
            if not line.startswith('setenv '):
                if line.strip() != '#':
                    lines.append(line)
                continue
            head, name, value = line.split()
            if value[0] == "'" and value[-1] == "'":
                value = value[1:-1]
            envdict[name] = value
except FileNotFoundError:
    lines = ['test $$ = %s && rm -f %s' % (os.getppid(), filename)]

proposal = os.environ.get('dat_proposal', envdict.get('dat_proposal', None))
if len(sys.argv) > 1:
    proposal = sys.argv[1]
elif proposal is None:
    if printit:
        print(USAGE)
        printit = False
    proposal = input('proposal: ')
envdict['dat_proposal'] = proposal

instrument = os.environ.get('dat_defspec', envdict.get('dat_defspec', None))
if len(sys.argv) > 2:
    instrument = sys.argv[2]
elif instrument is None:
    if printit:
        print(USAGE)
        printit = False
    instrument = input('instrument: ')
envdict['dat_defspec'] = instrument

if len(sys.argv) > 3:
    envdict['dat_defyear'] = sys.argv[3]
    
key = 'dat_spec_%s' % instrument
datspec = envdict.get(key, os.environ.get(key, None))
if datspec is None:
    if printit:
        print(USAGE)
        printit = False
    datspec = input('file path (containing ****** for numor): ')

elements = []
for spc in datspec.split(','):
    res = []
    for elm in spc.split('/'):
        if elm.startswith(instrument + '%%%%n'):
            res[-1] = proposal
        res.append(elm)
    elements.append('/'.join(res))
datspec = ','.join(elements)
envdict[key] = datspec

with open(filename, 'w') as f:
    for key, value in envdict.items():
        f.write("setenv %s '%s'\n#%s\n" % (key, value, os.environ.get(key, '')))
    f.write('\n'.join(lines))
    f.write('\n')

year = envdict.get('dat_defyear', time.strftime('%Y' , time.localtime()))
datspec = datspec.replace('%%%%', year)

if len(sys.argv) < 2:
    if printit:
        print(USAGE)
        printit = False

print('data file path:\n')
last = ''
for element in datspec.split(','):
    if '/' not in element:
        element = last.rsplit('.', 1)[0] + element
    print(element)
    last = element
