#!/usr/bin/env python

# Copyright (c) 2013, 2014 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# pylint: disable=F0401

import optparse
import os
import re
import shutil
import subprocess
import sys

from app_info import AppInfo
from customize import VerifyPackageName, CustomizeAll, \
                      ParseParameterForCompressor
from handle_permissions import permission_mapping_table
from manifest_json_parser import HandlePermissionList
from manifest_json_parser import ManifestJsonParser


NATIVE_LIBRARY = 'libxwalkcore.so'


def CleanDir(path):
  if os.path.exists(path):
    shutil.rmtree(path)


def AllArchitectures():
  return ("x86", "arm")


def ConvertArchNameToArchFolder(arch):
  arch_dict = {
      'x86': 'x86',
      'arm': 'armeabi-v7a'
  }
  return arch_dict.get(arch, None)


def AddExeExtensions(name):
  exts_str = os.environ.get('PATHEXT', '').lower()
  exts = [_f for _f in exts_str.split(os.pathsep) if _f]
  result = []
  result.append(name)
  for e in exts:
    result.append(name + e)
  return result


def RunCommand(command, verbose=False, shell=False):
  """Runs the command list, print the output, and propagate its result."""
  proc = subprocess.Popen(command, stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT, shell=shell)
  if not shell:
    output = proc.communicate()[0]
    result = proc.returncode
    if verbose:
      print(output.decode("utf-8").strip())
    if result != 0:
      print ('Command "%s" exited with non-zero exit code %d'
             % (' '.join(command), result))
      sys.exit(result)
    return output.decode("utf-8")


def Which(name):
  """Searches PATH for executable files with the given name, also taking
  PATHEXT into account. Returns the first existing match, or None if no matches
  are found."""
  for path in os.environ.get('PATH', '').split(os.pathsep):
    for filename in AddExeExtensions(name):
      full_path = os.path.join(path, filename)
      if os.path.isfile(full_path) and os.access(full_path, os.X_OK):
        return full_path
  return None


def GetAndroidApiLevel():
  """Get Highest Android target level installed.
     return -1 if no targets have been found.
  """
  target_output = RunCommand(['android', 'list', 'target', '-c'])
  target_regex = re.compile(r'android-(\d+)')
  targets = [int(i) for i in target_regex.findall(target_output)]
  targets.extend([-1])
  return max(targets)


def GetVersion(path):