#!/usr/bin/env python
#
# Copyright 2018-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>")
    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.11/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)

        # Files in bundled zlib that aren't needed to compile zlib are not included
        # in the tarball.
        if (relpath.startswith("zlib-1.2.11/contrib") or
            relpath.startswith("zlib-1.2.11/example") or
            relpath.startswith("zlib-1.2.11/test")):
            continue
        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)
    exit(1)