#!/usr/bin/python

# {C} Copyright 2018 Pensando Systems Inc. All rights reserved.

# Delphi compiler wrapper Program
# This calls the protoc compiler with delphi plugins

import argparse
import os
import subprocess

# increment this version whenever delphi protoc plugin is changed
# This will force all the proto files to be recompiled
version = "1.20"

# Wrapper to execute a command
def runProcess(exe):
    p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    while(True):
      retcode = p.poll() #returns None while subprocess is running
      line = p.stdout.readline()
      yield line
      if(retcode is not None):
        break

parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version='1.0.0')
parser.add_argument("-workspace", default='', help="Root of the workspace")
parser.add_argument("-outdir", required=True, help="Directory to place the generated files")
parser.add_argument("-input", nargs='+', required=True, help="input files")

# Parse the args
args = parser.parse_args()

# default value for some args
if args.workspace == '':
    if os.getenv("GOPATH", "") != '':
        args.workspace = os.getenv("GOPATH", "") + "/src/github.com/pensando/sw/"
    else:
        print "Can not determine the workspace"
        for line in runProcess("env"):
            print line
        exit(1)

# parameters for running protoc
protoc_exe = args.workspace + "nic/hal/third-party/google/x86_64/bin/protoc"
delphi_path = args.workspace + "nic/delphi/proto/delphi/"

# determine to import directories
import_dir = []
input_files = []
firstDir = ""
for inp in args.input:
    impath = "--proto_path ./" + os.path.dirname(inp) + "/"
    import_dir.append(impath)
    if firstDir == "":
        firstDir = os.path.dirname(inp)
    inpf = inp.replace(os.path.dirname(inp) + "/", "", 1)
    input_files.append(inpf)

import_dir = set(import_dir)
outDir = args.outdir + firstDir + "/"

print "outDir"
print outDir
print "input_files:"
print input_files

# command to run
runCmd = protoc_exe  + " -I ./ -I /usr/local/include/ -I nic/hal/third-party/google/include/ -I nic/third-party/gogo/protobuf/gogoproto -I " + args.workspace + " -I " + delphi_path + " " + " ".join(import_dir) + " --cpp_out=" + outDir + " --go_out=" + outDir + " --delphi_out=logtostderr=1,v=1:" + outDir + " " + " ".join(str(x) for x in input_files)
print "runCmd:"
print runCmd

# print "running command: " + runCmd

# run the protoc with delphi plugin
os.environ['LD_LIBRARY_PATH'] = 'nic/hal/third-party/google/x86_64/lib/'
for line in runProcess(runCmd.split()):
    print line
