#coding utf8
#!/usr/bin/python

import os
import sys
import threading
import subprocess

g_is_terminated = False
def is_terminated():
    return g_is_terminated

def printp_stdout(p):
    try:
        while not is_terminated():
            line = p.stdout.readline()
            if len(line) > 0:
                print(line, end = '')
    except Exception as e:
        print('build_script stdout error:' + e)

def printp_stderr(p):
    try:
        while is_terminated():
            line = p.stderr.readline()
            if len(line) > 0:
                print(line, end = '')
    except Exception as  e:
        print('build_script stderr error:' + e)

def need_rebuild():
    if not os.path.isfile('game_wrap.cxx'):
        return True
    s1 = os.stat('game_wrap.cxx')
    s2 = os.stat('game.i')
    return s1.st_mtime < s2.st_mtime

def rebuild():
    global g_is_terminated
    try:
        p = subprocess.Popen('swig -builtin -c++ -python -o game_wrap.cxx game.i',
                             stdin = subprocess.PIPE,
                             stdout = subprocess.PIPE,
                             stderr = None,
                             shell = True)
        t1 = threading.Thread(target = printp_stdout, args=(p, ))
        t2 = threading.Thread(target = printp_stderr, args=(p, ))
        t1.start()
        t2.start()
        p.wait()
        g_is_terminated = True
        t1.join()
        t2.join()
        sys.exit(p.returncode)
    except Exception as e:
        print('build_script rebuild error:' + str(e))

if need_rebuild():
    rebuild()
else:
    print('script files already is the latest')
