import os, sys, zipfile

ignored_files = [ '.gitignore', 'bitbucket-pipelines.yml', 'build-release.py', 'TODO.txt' ]
os.makedirs('./.release/', exist_ok=True)
version = sys.argv[1] if len(sys.argv) > 1 else '0.0.0'
version_t = tuple([ int(i) for i in version.split('.') ])
    
def zipdir(path: str, ziph: zipfile.ZipFile):
    for root, _, files in os.walk(path):
        absroot = os.path.abspath(root)
        if '.' in absroot or '__pycache__' in absroot:
            print(f'Skip {absroot}')
        else:
            print(f'Handle {absroot}')
            for file in files:
                if file in ignored_files:
                    print(f'Skip file: {file}')
                else:
                    src = os.path.join(root, file)
                    if file == '__init__.py':
                        nsrc = '/tmp/__init__.py'
                        with open(src, 'r') as s: lines = s.readlines()
                        for i in range(len(lines)):
                            l = lines[i]
                            if '$VERSION' in l:
                                lines[i] = f'    "version": {version_t},\n'
                        with open(nsrc, 'w') as d: d.writelines(lines)
                        src = nsrc
                    
                    print(f'Pack {src}')
                    ziph.write(
                        src, 
                        'shader_node_wizard/' + os.path.relpath(
                            os.path.join(root, file), 
                            path
                        )
                    )


with zipfile.ZipFile(
    f'./.release/shader_node_wizard-{version}.zip', 
    'w', 
    zipfile.ZIP_DEFLATED
    ) as zipf:
    zipdir('./', zipf)
