#!/usr/bin/env python3
# Copyright (C) 2018 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import re
import argparse
import tempfile
import subprocess
from compat import iteritems

SOURCE_TARGET = [
    ('protos/perfetto/trace_processor/trace_processor.proto',
     'python/perfetto/trace_processor/trace_processor.descriptor'),
    ('protos/perfetto/metrics/metrics.proto',
     'python/perfetto/trace_processor/metrics.descriptor'),
]

ROOT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))

SCRIPT_PATH = 'tools/gen_binary_descriptors'


def find_protoc():
  for root, _, files in os.walk(os.path.join(ROOT_DIR, 'out')):
    if 'protoc' in files:
      return os.path.join(root, 'protoc')
  return None


def generate(source, target, protoc_path, check_only):
  # delete=False + manual unlink is required for Windows. Otherwise the temp
  # file is kept locked exclusively and unaccassible until it's destroyed.
  with tempfile.NamedTemporaryFile(delete=False) as fdescriptor:
    subprocess.check_call([
        protoc_path,
        '--include_imports',
        '--proto_path=.',
        '--proto_path=' + \
            os.path.join(ROOT_DIR, "buildtools", "protobuf", "src"),
        '--descriptor_set_out={}'.format(fdescriptor.name),
        source,
    ], cwd=ROOT_DIR)

    s = fdescriptor.read()
    fdescriptor.close()
    os.remove(fdescriptor.name)

    if check_only:
      with open(target, 'rb') as old:
        old_content = old.read()
        if (s != old_content):
          raise AssertionError('Target {} does not match', target)
      return

    with open(target, 'wb') as out:
      out.write(s)


def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--check-only', action='store_true')
  parser.add_argument('--protoc')
  args = parser.parse_args()

  try:
    for source, target in SOURCE_TARGET:
      protoc = args.protoc or find_protoc()
      assert protoc, 'protoc not found specific (--protoc PROTOC_PATH)'
      assert os.path.exists(protoc), '{} does not exist'.format(protoc)
      if protoc is not args.protoc:
        print('Using protoc: {}'.format(protoc))
      generate(source, target, protoc, args.check_only)
  except AssertionError as e:
    if not str(e):
      raise
    print('Error: {}'.format(e))
    return 1


if __name__ == '__main__':
  exit(main())
