# Copyright (c) 2013 The Native Client 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 fcntl
import os
import shlex
import shutil
import subprocess
import sys

SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
NACLPORTS_ROOT = os.path.dirname(os.path.dirname(SCRIPT_DIR))

GS_BUCKET = 'naclports'
GS_URL = 'http://storage.googleapis.com/'
OUT_DIR = os.path.join(NACLPORTS_ROOT, 'out')
STAMP_DIR = os.path.join(OUT_DIR, 'stamp')
BUILD_ROOT = os.path.join(OUT_DIR, 'build')
PUBLISH_ROOT = os.path.join(OUT_DIR, 'publish')
TOOLS_DIR = os.path.join(NACLPORTS_ROOT, 'build_tools')
PACKAGES_ROOT = os.path.join(OUT_DIR, 'packages')

NACL_SDK_ROOT = os.environ.get('NACL_SDK_ROOT')
if sys.platform == "cygwin":
  NACL_SDK_ROOT = NACL_SDK_ROOT.replace('\\', '/')

VALID_KEYS = ['NAME', 'VERSION', 'URL', 'ARCHIVE_ROOT', 'LICENSE', 'DEPENDS',
              'MIN_SDK_VERSION', 'LIBC', 'DISABLED_LIBC', 'ARCH', 'CONFLICTS',
              'DISABLED_ARCH', 'URL_FILENAME', 'BUILD_OS', 'SHA1', 'DISABLED']
REQUIRED_KEYS = ['NAME', 'VERSION']

verbose = False

arch_to_pkgarch = {
  'x86_64': 'x86-64',
  'i686': 'i686',
  'arm': 'arm',
  'pnacl': 'pnacl',
}

# Inverse of arch_to_pkgarch
pkgarch_to_arch = {v:k for k, v in arch_to_pkgarch.items()}

if NACL_SDK_ROOT:
  sys.path.append(os.path.join(NACL_SDK_ROOT, 'tools'))


class Error(Exception):
  """General error used for all naclports-specific errors."""
  pass


class PkgFormatError(Error):
  """Error raised when package file is not valid."""
  pass


class DisabledError(Error):
  """Error raised when a package is cannot be built because it is disabled
  for the current configuration.
  """
  pass


def ParsePkgInfo(contents, filename, valid_keys=None, required_keys=None):
  """Parse the contents of the given file-object as a pkg_info file.

  Args:
    contents: pkg_info contents as a string.
    filename: name of file to use in error messages.
    valid_keys: list of keys that are valid in the file.
    required_keys: list of keys that are required in the file.

  Returns:
    A dictionary of the key, value pairs contained in the pkg_info file.

  Raises:
    PkgFormatError: if file is malformed, contains invalid keys, or does not
      contain all required keys.