#!/usr/bin/python

import os
import subprocess
import sys


def exit_with_non_zero(msg=None):
    print(msg)
    print("Your operation has failed !!.\nif you want to skip the checks, "
          "add --no-verify option or consult your team")
    sys.exit(1)


def get_added_files():
    std_out = get_subprocess_output(['git', 'diff', '--staged', '--name-only',
                                     '--diff-filter=A'])
    return std_out.splitlines()


def get_subprocess_output(command, shell=False):
    output_process = subprocess.Popen(command, shell=shell,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE
                                      )
    stdout, stderr = output_process.communicate()
    check_error(stderr)
    return stdout


def check_error(stderr):
    if stderr:
        print (stderr)
        raise StandardError(stderr)


def get_file_size(file_path):
    size_in_bytes = os.stat(file_path).st_size
    return size_in_bytes / (1024 * 1024)


def check_large_files():
    added_file_list = get_added_files()
    threshold_size = float(os.getenv("CYD_GIT_LARGE_FILE_SIZE", "1"))
    for file_name in added_file_list:
        file_size = get_file_size(file_name)
        if file_size > threshold_size:
            exit_with_non_zero(
                "Large file detected %s with size %s MB !!. " % (
                    file_name, file_size))


def main():
    check_large_files()


if __name__ == '__main__':
    main()
