#!/usr/bin/env python3
#
# Install Node packages in the install_node_packages.txt package list.

import sys
import subprocess
import distutils.spawn


def emulate_run(args, env=None):
    p = subprocess.Popen(args, env=env)
    if p.wait() == 0:
        return True
    return False


node = distutils.spawn.find_executable('node')
if sys.platform.startswith('win32'):
    npm = 'npm.cmd'
else:
    npm = distutils.spawn.find_executable('npm')

if __name__ == '__main__':
    if not node:
        node = distutils.spawn.find_executable('nodejs')
        if not node:
            print('error: node is not installed, skipping node module installation')
            sys.exit(1)

    if not npm:
        print('error: npm is not installed, skipping node module installation')
        sys.exit(1)

    error = False
    with open('install_node_packages.txt', 'r') as f:
        for line in f:
            line = line.strip()
            line = line.rstrip('\n')
            if line != '' and line[0] != '#':
                if not emulate_run([npm, 'install', '--global', line]):
                    error = True

    sys.exit(1 if error else 0)
