#!/usr/bin/env python3

# Copyright 2009-present MongoDB, Inc.
#
# 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.

"""Check that there are no missing .c or .h files in the release tarball.
"""
import os
import re
import sys

if len(sys.argv) != 3:
    print("Usage: python check_files.py"
          " <src directory from repo>"
          " <src directory produced by tarball>")
    sys.exit(1)

REPO_SRC_DIR = sys.argv[1]
TAR_SRC_DIR = sys.argv[2]

pattern = re.compile(r".*\.(c|h)$")

repo_src_files = set()
tar_src_files = set()

# Files that are generated by cmake are expected not to be in the repository.
cmake_produced = [
    "libbson/src/bson/bson-version.h",
    "libmongoc/src/mongoc/mongoc-version.h",
    "zlib-1.2.13/zconf.h",
]

for root, dirs, files in os.walk(REPO_SRC_DIR):
    for file in files:
        relpath = os.path.relpath(os.path.join(root, file), REPO_SRC_DIR)

        if pattern.match(relpath):
            repo_src_files.add(relpath)

for root, dirs, files in os.walk(TAR_SRC_DIR):
    for file in files:
        relpath = os.path.relpath(os.path.join(root, file), TAR_SRC_DIR)
        if relpath in cmake_produced:
            continue
        if pattern.match(relpath):
            tar_src_files.add(relpath)

if tar_src_files != repo_src_files:
    print("Files produced from tarball differ from repository")
    print("Tarball produced the following files NOT in repository")
    for file in sorted(tar_src_files.difference(repo_src_files)):
        print(" " + file)
    print("Repository has the following files NOT in tarball")
    for file in sorted(repo_src_files.difference(tar_src_files)):
        print(" " + file)
    sys.exit(1)
