#!/usr/bin/env python
# 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.

import os
import re
import subprocess
import sys

PROTOS = (
  'protos/perfetto/config/chrome/chrome_config.proto',
  'protos/perfetto/config/inode_file/inode_file_config.proto',
  'protos/perfetto/config/process_stats/process_stats_config.proto',
  'protos/perfetto/config/data_source_config.proto',
  'protos/perfetto/config/ftrace/ftrace_config.proto',
  'protos/perfetto/config/test_config.proto',
  'protos/perfetto/config/trace_config.proto',
)

MERGED_OUT_PROTO = 'protos/perfetto/config/perfetto_config.proto'

REPLACEMENT_HEADER = '''
// AUTOGENERATED - DO NOT EDIT
// ---------------------------
// This file has been generated by
// AOSP://external/perfetto/%s
// merging the perfetto config protos.
// This fused proto is intended to be copied in:
//  - Android tree, for statsd.
//  - Google internal repos.

syntax = "proto2";

package perfetto.protos;
'''

def main():
  root_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
  merged_content = ''
  for proto in PROTOS:
    path = os.path.join(root_dir, proto)
    with open(path) as f:
      content = f.read()

    # Remove header
    header = re.match(r'\/\*(?:.|\s)*?package.*;\n', content)
    header = header.group(0)
    content = content[len(header):]
    if merged_content == '':
      merged_content += REPLACEMENT_HEADER.lstrip() % __file__
    content = re.sub(r'^import.*?\n', '', content, flags=re.MULTILINE)
    content = re.sub(r'TODO\([^)]*\):', 'TODO:', content)
    merged_content += '\n// Begin of %s\n' % proto
    merged_content += content
    merged_content += '\n// End of %s\n' % proto

  out_path = os.path.join(root_dir, MERGED_OUT_PROTO)

  prev_content = None
  if os.path.exists(out_path):
    with open(out_path, 'rb') as fprev:
      prev_content = fprev.read()

  if prev_content == merged_content:
    return 0

  if '--check-only' in sys.argv:
    return 1

  print 'Updating %s' % MERGED_OUT_PROTO
  with open(out_path, 'wb') as fout:
    fout.write(merged_content)
  return 0

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