#!/usr/bin/env python3

# Copyright 2025 Google LLC
#
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
import os
import subprocess
import sys
import sysconfig
import textwrap

EMSDK_ROOT = os.path.join('third_party', 'emsdk')

EMSDK_PATH = os.path.join(EMSDK_ROOT, 'emsdk.py')
EMSDK_CONFIG_PATH = os.path.join(EMSDK_ROOT, '.emscripten')

EMSDK_VERSION = '4.0.3'

def main(args):
    parser = argparse.ArgumentParser()
    parser.add_argument('--node', help='Path to nodejs binary.')
    parser.add_argument('--llvm', help='Path to LLVM binaries.')
    options = parser.parse_args();

    # Install and activate the default dependencies for emsdk.
    try:
        subprocess.check_call([sys.executable, EMSDK_PATH, 'install', EMSDK_VERSION])
    except subprocess.CalledProcessError:
        print ('Failed to install emsdk')
        return 1
    try:
        subprocess.check_call([sys.executable, EMSDK_PATH, 'activate', EMSDK_VERSION])
    except subprocess.CalledProcessError:
        print ('Failed to activate emsdk')
        return 1

    # Back up the .emscripten file generated by emsdk.
    os.replace(EMSDK_CONFIG_PATH, EMSDK_CONFIG_PATH + ".emsdk_original")
    # Override the default generated .emscripten file for certain binaries.
    em_config = textwrap.dedent(f"""\
        import os
        emsdk_path = os.path.dirname(os.getenv('EM_CONFIG')).replace('\\\\', '/')
        NODE_JS = emsdk_path + '/../../{options.node}'
        LLVM_ROOT = emsdk_path + '/../../{options.llvm}'
        BINARYEN_ROOT = emsdk_path + '/upstream'
        EMSCRIPTEN_ROOT = emsdk_path + '/upstream/emscripten'
        """)
    with open(EMSDK_CONFIG_PATH, 'w') as f:
        f.write(em_config)


if __name__ == '__main__':
  sys.exit(main(sys.argv))
