#!/bin/env python3

import zipfile
import sys
import shutil
import os
import pathlib

macos_template = "isometric-park-fna/bin/isometric-park-template.app"
windows_template = "isometric-park-fna/bin/isometric-park-windows-template"

sourcedir = "isometric-park-fna/bin/Release"

def make_windows(suffix="new"):
    new_name = windows_template[:-9] + "-" + suffix 

    # shutil.rmtree(new_name)
    shutil.copytree(windows_template, new_name)

    for (dirpath, _dirname, files) in os.walk(sourcedir):
        for file in files:
            source = pathlib.Path(dirpath) / file
            destination = pathlib.Path(new_name) / os.path.relpath(sourcedir, dirpath) / pathlib.Path(file)

            print(source, destination)

            if source.is_dir() and not destination.exists():
                shutil.copytree(source, destination)
            else:
                shutil.copy2(source, destination)

    shutil.move(pathlib.Path(new_name) / "isometric-park-fna.exe",
                pathlib.Path(new_name) / "isometric-park.exe")

    with zipfile.ZipFile(new_name + ".zip", "w",
                         #Windows doesn't natively support other formats
                         #(besides uncompressed) in my testing:
                         compression=zipfile.ZIP_DEFLATED) as f:
        for (dirpath, _dirname, files) in os.walk(sourcedir):
            for file in files:
                source = pathlib.Path(dirpath) / file
                f.write(source)

def make_macos(suffix="new"):

    new_name = macos_template[:-4] + "-" + suffix + ".app" + "/"

    # shutil.rmtree(new_name)
    shutil.copytree(macos_template, new_name)

    for (dirpath, _dirname, files) in os.walk(sourcedir):
        for file in files:
            source = pathlib.Path(dirpath) / file
            destination = pathlib.Path(new_name) / "Contents" / "Resources" / pathlib.Path(file)

            print(source, destination)

            if source.is_dir() and not destination.exists():
                shutil.copytree(source, destination)
            else:
                shutil.copy2(source, destination)

    shutil.move(pathlib.Path(new_name) / "Contents" / "Resources" / "isometric-park-fna.exe",
                pathlib.Path(new_name) / "Contents" / "Resources" / "isometric-park.exe")


def main():
    if len(sys.argv) > 1:
        command = sys.argv[1]

        if command.lower() == "macos":
            if len(sys.argv) > 2:
                make_macos(sys.argv[2])
            else:
                make_macos()
        elif command.lower() in ("win", "windows"):
            if len(sys.argv) > 2:
                make_windows(sys.argv[2])
            else:
                make_windows()
    else:
        pass



if __name__ == '__main__':
    main()
