#!/usr/bin/env python3
#
# Copyright (C) 2021 The Android Open main 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 argparse
import os
import pathlib
import sys


def process_owners(main_dir, main_branch, tracking_dirs):
  # walk the tree ...
  for subdir, _, files in os.walk(main_dir):
    for file in files:
      # ... and for each OWNERS file in the main ...
      if file == 'OWNERS':
        rel_dir = pathlib.Path(subdir[len(main_dir.name) + 1:])
        owners = rel_dir / file

        for tracking_dir in tracking_dirs:
          target = tracking_dir / owners
          comment_line = (f'# include OWNERS from the authoritative '
                          f'{main_branch} branch\n')
          include_line = f'include kernel/common:{main_branch}:/{owners}\n'

          # ... either add a new file with include directive ...
          if not target.is_file():
            with open(target, 'w') as file:
              file.writelines([comment_line, include_line])

          # ... or ensure the include directive is in the file
          else:
            with open(target) as file:
              contents = file.readlines()
            if include_line not in contents:
              with open(target, 'w') as file:
                file.writelines([comment_line, include_line, '\n'] + contents)


def is_dir(dirname):
  result = pathlib.Path(dirname)
  if not result.is_dir():
    raise argparse.ArgumentTypeError(f'{dirname} is not a directory')
  else:
    return result


def main():
  parser = argparse.ArgumentParser()

  parser.add_argument(
      'main_dir', type=is_dir, help='main directory to synchronize from')
  parser.add_argument('main_branch', help='main branch name'),
  parser.add_argument(
      'tracking_dir', type=is_dir, nargs='+', help='tracking directory to synchronize to')

  args = parser.parse_args()

  process_owners(args.main_dir, args.main_branch, args.tracking_dir)


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