#!/usr/bin/python3

import subprocess
import os
import json
import shutil


def run_cmd(command):
    ret = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8')
    if ret.returncode == 0:
        print('success:', ret.stdout, ret.stderr)
    else:
        print('error:', ret.stdout, ret.stderr)


if __name__ == '__main__':
    run_cmd(['npm', 'run', 'build-rte-runtime-lite'])

    # Create a temp folder to put those files which rte-runtime-lite contains.
    try:
        os.mkdir('temp')
    except Exception as e:
        print('Error to mkdir.', e)

    # 1. Copy build results
    shutil.copytree('build', 'temp/build')

    # 2. Create index.js of rte-runtime-lite
    shutil.move('temp/build/rte_runtime_lite_index.js', 'temp/build/index.js')

    # 2. copy index.d.js of rte-runtime-lite
    shutil.copyfile('src/rte_runtime_lite_index.d.ts', 'temp/build/index.d.ts')

    # modify the package name to 'rte-runtime-lite'
    with open('package.json', 'r') as pkg:
        pkg_json = json.load(pkg)

        pkg_json['name'] = '@agora-rte/rte-runtime-lite'

        with open('temp/package.json', 'w') as dest:
            json.dump(pkg_json, dest, indent=2)

    # publish to npm repository.
    run_cmd(['npm', 'publish'])

    # cleanup
    shutil.rmtree('temp')
    shutil.rmtree('build')
    os.remove('tsconfig.tsbuildinfo')
