#!/usr/bin/env python3
"""
wasiconfigure is a helper script that runs ./configure for you,
setting the environment variables to use wasic. Usage:
  wasiconfigure ./configure [FLAGS]
You can also use this for other configure-like stages.
"""
import os
import sys
from subprocess import check_call, CalledProcessError

def run():
    if len(sys.argv) < 2 or sys.argv[1] in ('--version', '--help'):
        print('''\
wasiconfigure is a helper for configure, setting various environment
variables so that wasic etc. are used. Typical usage:

  wasiconfigure ./configure [FLAGS]

(but you can run any command instead of configure)''', file=sys.stderr)
        return 1

    args = sys.argv[1:]
    if 'cmake' in args:
        print('error: wasiconfigure is not intended for cmake projects', file=sys.stderr)
        return 1

    if 'WASI_SDK_PATH' not in os.environ:
        print('Error: WASI_SDK_PATH not set!', file=sys.stderr)
        return 1

    # Get absolute path to our wasic wrapper
    our_path = os.path.dirname(os.path.abspath(__file__))

    # Set up the environment for configure
    env = os.environ.copy()

    # Core compiler tools
    env['CC'] = 'wasic'
    env['CXX'] = 'wasic++'
    env['LD'] = os.path.join(env['WASI_SDK_PATH'], 'bin/wasm-ld')
    env['LDSHARED'] = os.path.join(env['WASI_SDK_PATH'], 'bin/clang')
    env['AR'] = os.path.join(env['WASI_SDK_PATH'], 'bin/llvm-ar')
    env['NM'] = os.path.join(env['WASI_SDK_PATH'], 'bin/llvm-nm')
    env['RANLIB'] = os.path.join(env['WASI_SDK_PATH'], 'bin/llvm-ranlib')
    env['STRIP'] = os.path.join(env['WASI_SDK_PATH'], 'bin/llvm-strip')
    env['OBJDUMP'] = os.path.join(env['WASI_SDK_PATH'], 'bin/llvm-objdump')

    # Host tools point directly to system clang
    env['HOST_CC'] = '/usr/bin/clang'
    env['HOST_CXX'] = '/usr/bin/clang++'
    env['HOST_CFLAGS'] = '-O2'
    env['HOST_CXXFLAGS'] = '-O2'
    env['HOST_LDFLAGS'] = '-O2'

    # Cross compilation flags
    env['CFLAGS'] = env.get('CFLAGS', '') + ' -D_WASI_EMULATED_SIGNAL'
    env['LDFLAGS'] = env.get('LDFLAGS', '') + ' -lwasi-emulated-signal'
    env['CROSS_COMPILE'] = os.path.join(our_path, 'wasi')

    # Add our directory to PATH
    env['PATH'] = our_path + os.pathsep + env.get('PATH', '')

    print('configure: ' + ' '.join(args), file=sys.stderr)
    try:
        check_call(args, env=env)
        return 0
    except CalledProcessError as e:
        return e.returncode

if __name__ == '__main__':
    sys.exit(run())