#!/usr/bin/env python

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

"""Creates a script to run an "_incremental" .apk."""

import argparse
import os
import pprint
import sys

sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, 'gyp'))

from pylib import constants
from util import build_utils


SCRIPT_TEMPLATE = """\
#!/usr/bin/env python
#
# This file was generated by:
#     //build/android/incremental_install/create_install_script.py

import os
import subprocess
import sys

def main():
  script_directory = os.path.dirname(__file__)

  def resolve_path(path):
    return os.path.abspath(os.path.join(script_directory, path))

  cmd_path = resolve_path({cmd_path})
  cmd_args = [cmd_path] + {cmd_args}
  cmd_path_args = {cmd_path_args}
  for arg, path in cmd_path_args:
    if arg:
      cmd_args.append(arg)
    cmd_args.append(resolve_path(path))

  return subprocess.call(cmd_args + sys.argv[1:])

if __name__ == '__main__':
  sys.exit(main())
"""


def _ParseArgs(args):
  args = build_utils.ExpandFileArgs(args)
  parser = argparse.ArgumentParser()
  build_utils.AddDepfileOption(parser)
  parser.add_argument('--script-output-path',
                      help='Output path for executable script.',
                      required=True)
  parser.add_argument('--output-directory',
                      help='Path to the root build directory.',
                      default='.')
  parser.add_argument('--apk-path',
                      help='Path to the .apk to install.',
                      required=True)
  parser.add_argument('--split',
                      action='append',
                      dest='splits',
                      default=[],
                      help='A glob matching the apk splits. '
                           'Can be specified multiple times.')
  parser.add_argument('--lib-dir',
                      help='Path to native libraries directory.')
  parser.add_argument('--dex-file',
                      action='append',
                      default=[],
                      dest='dex_files',
                      help='List of dex files to include.')
  parser.add_argument('--dex-file-list',
                      help='GYP-list of dex files.')

  options = parser.parse_args(args)
  options.dex_files += build_utils.ParseGypList(options.dex_file_list)
  return options


def main(args):
  options = _ParseArgs(args)

  def relativize(path):
    return os.path.relpath(path, os.path.dirname(options.script_output_path))

  installer_path = os.path.join(constants.DIR_SOURCE_ROOT, 'build', 'android',
                                'incremental_install', 'installer.py')
  installer_path = relativize(installer_path)

  path_args = [
      ('--output-directory', relativize(options.output_directory)),
      (None, relativize(options.apk_path)),
  ]

  if options.lib_dir:
    path_args.append(('--lib-dir', relativize(options.lib_dir)))

  if options.dex_files:
    for dex_file in options.dex_files:
      path_args.append(('--dex-file', relativize(dex_file)))

  for split_arg in options.splits:
    path_args.append(('--split', relativize(split_arg)))

  with open(options.script_output_path, 'w') as script:
    script.write(SCRIPT_TEMPLATE.format(
        cmd_path=pprint.pformat(installer_path),
        cmd_args='[]',
        cmd_path_args=pprint.pformat(path_args)))

  os.chmod(options.script_output_path, 0750)

  if options.depfile:
    build_utils.WriteDepfile(
        options.depfile,
        build_utils.GetPythonDependencies())


if __name__ == '__main__':
  sys.exit(main(sys.argv[1:]))
