#!/bin/env python

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import shlex
import shutil
import subprocess
import sys

"""
Invoke as:

    thrift/compiler/test/build_fixtures $BUILDDIR

where $BUILDDIR/thrift/compiler/thrift is the thrift compiler
"""

def ascend_find_exe(path, target):
    if not os.path.isdir(path):
        path = os.path.dirname(path)
    while True:
        test = os.path.join(path, target)
        if os.access(test, os.X_OK):
            return test
        parent = os.path.dirname(path)
        if os.path.samefile(parent, path):
            return None
        path = parent

def ascend_find_dir(path, target):
    if not os.path.isdir(path):
        path = os.path.dirname(path)
    while True:
        test = os.path.join(path, target)
        if os.path.isdir(test):
            return test
        parent = os.path.dirname(path)
        if os.path.samefile(parent, path):
            return None
        path = parent

def read_lines(path):
    with open(path, 'r') as f:
        return f.readlines()

exe = os.path.join(os.getcwd(), sys.argv[0])
buildDir = sys.argv[1]
thriftRel = os.path.join(buildDir, 'thrift/compiler/thrift')
thrift = ascend_find_exe(exe, thriftRel)
fixtureDir = ascend_find_dir(exe, 'thrift/compiler/test/fixtures')
fixtureNames = [
    f
    for f in os.listdir(fixtureDir)
    if os.path.isfile(os.path.join(fixtureDir, f, 'cmd'))
]

for name in fixtureNames:
    cwd = os.path.join(fixtureDir, name)
    for fn in set(os.listdir(cwd)) - set(['cmd', 'src']):
        if fn.startswith('.'):
            continue
        shutil.rmtree(os.path.join(cwd, fn))
    cmds = read_lines(os.path.join(cwd, 'cmd'))
    for cmd in cmds:
        subprocess.check_call(
            [thrift, "-r", "--gen"] + shlex.split(cmd.strip()),
            cwd=cwd,
            close_fds=True,
        )
