# Copyright 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.

"""Client configuration management.

This module holds the code for detecting and configuring the current client and
it's output directories.
It is responsible for writing out the client specific plugins that tell the
rest of the cr tool what the client is capable of.
"""

import os
import pprint
import sys

import cr
import cr.auto.build
import cr.auto.client

# The config version currently supported.
VERSION = 0.5
# The default directory name to store config inside
CLIENT_CONFIG_PATH = '.cr'
# The partial filename to add to a directory to get it's config file.
CLIENT_CONFIG_FILE = os.path.join(CLIENT_CONFIG_PATH, 'config.py')
# The format string for the header of a config file.
CONFIG_FILE_PREFIX = """
# This is an autogenerated file
# it *will* be overwritten, and changes may lost
# The system will autoload any other python file in the same folder.

import cr

OVERRIDES = cr.Config.From("""
# The format string for each value in a config file.
CONFIG_VAR_LINE = '\n  {0} = {1!r},'
# The format string for the tail of a config file.
CONFIG_FILE_SUFFIX = '\n)\n'
# The name of the gclient config file
GCLIENT_FILENAME = '.gclient'

# The default config values installed by this module.
DEFAULT = cr.Config.From(
    CR_ROOT_PATH=os.path.join('{GOOGLE_CODE}'),
    CR_CLIENT_NAME='chromium',
    CR_CLIENT_PATH=os.path.join('{CR_ROOT_PATH}', '{CR_CLIENT_NAME}'),
    CR_SRC=os.path.join('{CR_CLIENT_PATH}', 'src'),
    CR_BUILD_DIR=os.path.join('{CR_SRC}', '{CR_OUT_FULL}'),
)


def DetectClient(context):
  # Attempt to detect the current client from the cwd
  # See if we can detect the source tree root
  client_path = os.getcwd()
  while (client_path and
         not os.path.exists(os.path.join(client_path, GCLIENT_FILENAME))):
    old = client_path
    client_path = os.path.dirname(client_path)