import zipfile
import glob
from os import path


class zip_backup:
    root_dir = ''

    ignore = []
    backup_list = []

    def ignore_list(self):
        gitignore = self.root_dir + '\\.gitignore'
        if not path.exists(gitignore):
            pass
        with open(gitignore, 'r') as f:
            for line in f.readlines():
                line = line.strip().replace('/', '\\').lower()
                if line[:1] == '*':
                    if line[-1] == '*':
                        line = line[1:-1]
                    else:
                        line = line[1:] + '\\'
                else:
                    line = '\\' + line + '\\'
                self.ignore.append(line)

    def ignored(self, filename):
        rel_filename = '\\' + filename.replace(self.root_dir, '').lower() + '\\'

        for e in self.ignore:
            if e in rel_filename:
                return True
        return False

    def check_dir(self, current_dir):
        if self.root_dir == '':
            self.root_dir = current_dir
            self.ignore_list()

        for entry in glob.glob(current_dir + '\\*'):
            if path.isdir(entry):
                self.check_dir(entry)
            elif not self.ignored(entry):
                self.backup_list.append(entry)

    def zip_to_file(self, zip_file):
        with zipfile.ZipFile(zip_file, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zip:
            for e in self.backup_list:
                zip.write(e)


if __name__ == '__main__':
    z_backup = zip_backup()
    z_backup.check_dir('C:\\GAPS_Autosys')
    # print(backup_list[:10])
    z_backup.zip_to_file('C:\\GAPS_Autosys\\Test.zip')
