# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import errno
import os
import re
import subprocess
import sys

"""
Copies the given "win tool" (which the toolchain uses to wrap compiler
invocations) and the environment blocks for the 32-bit and 64-bit builds on
Windows to the build directory.

The arguments are the visual studio install location and the location of the
win tool. The script assumes that the root build directory is the current dir
and the files will be written to the current directory.
"""


def ExtractImportantEnvironment():
  """Extracts environment variables required for the toolchain from the
  current environment."""
  # This list should be kept synchronized with _ExtractImportantEnvironment from
  # tools/gyp/pylib/gyp/msvs_emulation.py.
  envvars_to_save = (
      'goma_.*',  # TODO(scottmg): This is ugly, but needed for goma.
      'include',  # Needed by midl compiler.
      'lib',
      'libpath',
      'path',
      'pathext',
      'systemroot',
      'temp',
      'tmp',
      )
  result = {}
  for envvar in envvars_to_save:
    if envvar in os.environ:
      envvar = envvar.lower()
      if envvar == 'path':
        # Our own rules (for running gyp-win-tool) and other actions in
        # Chromium rely on python being in the path. Add the path to this
        # python here so that if it's not in the path when ninja is run
        # later, python will still be found.
        result[envvar.upper()] = os.path.dirname(sys.executable) + \
            os.pathsep + os.environ[envvar]
      else:
        result[envvar.upper()] = os.environ[envvar]
  for required in ('SYSTEMROOT', 'TEMP', 'TMP'):
    if required not in result:
      raise Exception('Environment variable "%s" '
                      'required to be set to valid path' % required)
  return result


def FormatAsEnvironmentBlock(envvar_dict):
  """Format as an 'environment block' directly suitable for CreateProcess.
  Briefly this is a list of key=value\0, terminated by an additional \0. See
  CreateProcess documentation for more details."""
  block = ''
  nul = '\0'
  for key, value in envvar_dict.iteritems():
    block += key + '=' + value + nul
  block += nul
  return block


def CopyTool(source_path):
  """Copies the given tool to the current directory, including a warning not
  to edit it."""
  with open(source_path) as source_file:
    tool_source = source_file.readlines()

  # Add header and write it out to the current directory (which should be the
  # root build dir).
  with open("gyp-win-tool", 'w') as tool_file:
    tool_file.write(''.join([tool_source[0],
                             '# Generated by setup_toolchain.py do not edit.\n']
                            + tool_source[1:]))

if len(sys.argv) != 4:
  print('Usage setup_toolchain.py '
        '<visual studio path> <win tool path> <win sdk path>')
  sys.exit(2)
vs_path = sys.argv[1]
tool_source = sys.argv[2]
win_sdk_path = sys.argv[3]

CopyTool(tool_source)

important_env_vars = ExtractImportantEnvironment()
path = important_env_vars["PATH"].split(";")

# Add 32-bit compiler path to the beginning and write the block.
path32 = [os.path.join(vs_path, "VC\\BIN\\amd64_x86")] + \
         [os.path.join(win_sdk_path, "bin\\x86")] + \
         path
important_env_vars["PATH"] = ";".join(path32)
environ = FormatAsEnvironmentBlock(important_env_vars)
with open('environment.x86', 'wb') as env_file:
  env_file.write(environ)

# Add 64-bit compiler path to the beginning and write the block.
path64 = [os.path.join(vs_path, "VC\\BIN\\amd64")] + \
         [os.path.join(win_sdk_path, "bin\\x64")] + \
         path
important_env_vars["PATH"] = ";".join(path64)
environ = FormatAsEnvironmentBlock(important_env_vars)
with open('environment.x64', 'wb') as env_file:
  env_file.write(environ)
