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

USAGE = """
Usage:

    getdatafilepath <instrument> <year> <number>

get datafile path
"""

if len(sys.argv) != 4:
    print(USAGE)
    sys.exit()

instrument = sys.argv[1]
year = sys.argv[2]
number = int(sys.argv[3])
key = 'dat_spec_%s' % instrument
last = ''
for datspec in os.environ[key].replace('%%%%', year).split(','):
    if '/' not in datspec:
        datspec = last.rsplit('.', 1)[0]+datspec
    last = datspec
    for i in range(10,0,-1):
        pat = '*' * i
        if datspec.find(pat) >= 0:
            break
    else:
       pat = None

    if pat:
        fmt = '%%.%dd' % len(pat)
        datspec = datspec.replace(pat, fmt % number)
    if year < '2020':
        datspec = datspec.replace('###', '%.3d' % (number // 1000))
        if os.path.isfile(datspec):
            print(datspec)
            break
    else:
        datspec = datspec.replace('###', '*')
        files = glob(datspec)
        if len(files) == 1:
           print(files[0])
           break
else:
    print('%s:%s:%d' % (instrument, year, number))
