#!/usr/bin/python

#
# This is s small wrapper around JCC that tries to avoid crash in JCC during JNI_CrateJavaVM on armel, 
# armhf, mips, mipsel arches.
#
# The idea is to read command-line options via stdin
#
# Usage: replace jcc calls with wrapper call:
#
# Before:
#   python2.7 -m jcc.__main__ --jar file1.jar ... --build
#
# After:
#   debian/jcc_wrapper python2.7 -m jcc.__main__ --jar file1.jar ... --build
#
# jcc_wrapper will read all arguments from sys.argv, invoke itself with --stdin arg and
# pass parameters to JCC without touching of sys.argv
#
# http://mail-archives.apache.org/mod_mbox/lucene-pylucene-dev/201608.mbox/<20160808110126.jmb6hamgvxm2aeie@debpad.local
#

import os
import sys
import subprocess

if len(sys.argv) > 1 and sys.argv[1] == '--stdin':
    # Child process. Read options and call jcc
    args = sys.stdin.read().split('\n')
    
    # Get rid of -m jcc.__main__ (expected to be first two args)
    if len(args) > 2 and args[1] == '-m':
        del args[1:3]

    # python -m jcc fills sys.argv[0] with path to module. Emulate this
    import jcc
    args[0] = os.path.join(jcc.__path__[0], '__main__.py')

    from jcc import cpp
    cpp.jcc(args)
else:
    # parent process. Read opts, and pass them to child
    # expected args: jcc_wrapper python2.7 -m jcc.__main__ ...
    proc = subprocess.Popen([sys.argv[1], sys.argv[0], '--stdin'], stdin=subprocess.PIPE)
    proc.stdin.write('\n'.join(sys.argv[1:]))
    proc.stdin.close()
    sys.exit(proc.wait())
