#!/usr/bin/env python3
# Copyright (c) 2017-2026 Soft8Soft, LLC. All rights reserved.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#
#
#
#
#
#

import os, platform, re, shutil, sys

SUPPORTED_BLENDER_VERSIONS = ['4.5', '5.0', '5.1', '5.2']

def copyExtension(blendConfDir):

    rootDir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..'))

    srcPath = os.path.join(rootDir, 'addons', 'verge3d')

    dstParentPath = os.path.join(blendConfDir, 'extensions', 'soft8soft')

    os.makedirs(dstParentPath, exist_ok=True)

    dstPath = os.path.join(dstParentPath, 'verge3d')

    if os.path.isdir(dstPath):
        shutil.rmtree(dstPath)

    shutil.copytree(srcPath, dstPath)

    srcInitScript = os.path.join(srcPath, '__init__.py')
    dstInitScript = os.path.join(dstPath, '__init__.py')

    with open(srcInitScript, 'r', encoding='utf-8') as fin:
        with open(dstInitScript, 'w', encoding='utf-8') as fout:
            for line in fin:
                fout.write(re.sub('(ROOT_DIR) *=.*', 'ROOT_DIR = r\'{}\''.format(rootDir.replace('\\', '\\\\')), line))

    startupPath = os.path.join(blendConfDir, 'scripts', 'startup')
    os.makedirs(startupPath, exist_ok=True)

    shutil.copy2(os.path.join(srcPath, 'setup', 'startup.py'), os.path.join(startupPath, 'verge3d.py'))
    shutil.copy2(os.path.join(srcPath, 'setup', 'startup_migrate.py'), os.path.join(startupPath, 'soft8soft_repo_migrate.py'))

def removeExtension(blendConfDir, oldAddon=False):

    removed = False

    if oldAddon:
        path = os.path.join(blendConfDir, 'scripts', 'addons', 'verge3d')
    else:
        path = os.path.join(blendConfDir, 'extensions', 'soft8soft', 'verge3d')

    if os.path.isdir(path):
        shutil.rmtree(path)
        removed = True

    if not oldAddon:
        startupScript = os.path.join(blendConfDir, 'scripts', 'startup', 'verge3d.py')
        if os.path.isfile(startupScript):
            os.remove(startupScript)
            removed = True
        migrateScript = os.path.join(blendConfDir, 'scripts', 'startup', 'soft8soft_repo_migrate.py')
        if os.path.isfile(migrateScript):
            os.remove(migrateScript)
            removed = True

    return removed

def traverseBlenderDirs(doInstall, blendVersions):
    system = platform.system()

    if system == 'Windows':
        blendDir = os.path.expandvars(r'%USERPROFILE%\AppData\Roaming\Blender Foundation\Blender')
    elif system == 'Darwin':
        blendDir = os.path.expandvars(r'$HOME/Library/Application Support/Blender')
    else:
        blendDir = os.path.expandvars(r'$HOME/.config/blender')

    for blendVer in blendVersions:
        blendVerDir = os.path.join(blendDir, blendVer)
        if doInstall:
            print('Installing Verge3D extension for Blender {}'.format(blendVer))
            copyExtension(blendVerDir)

            removeExtension(blendVerDir, True)
        else:
            if removeExtension(blendVerDir):
                print('Removed Verge3D extension for Blender {}'.format(blendVer))

if __name__ == '__main__':
    if len(sys.argv) <= 1 or sys.argv[1].lower() == 'install':
        doInstall = True
    elif len(sys.argv) > 1 and sys.argv[1].lower() == 'uninstall':
        doInstall = False
    else:
        print('Wrong script arguments')
        sys.exit(1)

    if len(sys.argv) > 2:
        ver = sys.argv[2]
        if ver in SUPPORTED_BLENDER_VERSIONS:
            versions = [ver]
        else:
            print('Invalid or unsupported version:', ver)
            sys.exit(1)
    else:
        versions = SUPPORTED_BLENDER_VERSIONS

    traverseBlenderDirs(doInstall, versions)
