#!/usr/bin/env python3
# Copyright (c) 2017-2026 Soft8Soft, LLC. All rights reserved.
#
# Use of this software is subject to the terms of the Verge3D license
# agreement provided at the time of installation or download, or which
# otherwise accompanies this software in either electronic or hard copy form.

import os, platform, sys

SUPPORTED_MAYA_VERSIONS = ['2024', '2025', '2026', '2027']

def registerPlugin(conf, envPathSep):
    baseDir = os.path.dirname(os.path.abspath(__file__))
    pluginPath = os.path.normpath(os.path.join(baseDir, '..'))

    lines = []

    with open(conf, 'r',  encoding='utf-8') as fin:
        lines = fin.readlines()

    pluginLine = -1

    for n in range(len(lines)):
        if pluginPath in lines[n]:
            return

        if u'MAYA_PLUG_IN_PATH' in lines[n]:
            pluginLine = n
            break

    if pluginLine > -1:
        lineSplit = lines[pluginLine].split('=')

        varName = lineSplit[0].strip()
        existingPaths = lineSplit[1].strip().split(envPathSep)

        filteredPaths = []
        for path in existingPaths:
            if not ('verge3d' in path.lower() and 'maya_plugin' in path.lower()):
                filteredPaths.append(path)

        lines[pluginLine] = varName + '=' + pluginPath + envPathSep + envPathSep.join(filteredPaths) + '\n'
    else:
        if len(lines) and lines[-1][-1] != '\n':
            lines[-1] = lines[-1] + '\n'
        lines.append(u'MAYA_PLUG_IN_PATH=' + pluginPath + '\n')

    with open(conf, 'w', encoding='utf-8') as f:
        f.writelines(lines)

def unregisterPlugin(conf, envPathSep):
    lines = []

    with open(conf, 'r',  encoding='utf-8') as fin:
        lines = fin.readlines()

    pluginLine = -1

    for n in range(len(lines)):
        if u'MAYA_PLUG_IN_PATH' in lines[n]:
            pluginLine = n
            break

    if pluginLine > -1:
        lineSplit = lines[pluginLine].split('=')

        varName = lineSplit[0].strip()
        existingPaths = lineSplit[1].strip().split(envPathSep)

        filteredPaths = []
        for path in existingPaths:
            if not ('verge3d' in path.lower() and 'maya_plugin' in path.lower()):
                filteredPaths.append(path)

        lines[pluginLine] = varName + '=' + envPathSep.join(filteredPaths) + '\n'

    with open(conf, 'w', encoding='utf-8') as f:
        f.writelines(lines)

def traverseMayaDirs(doInstall, mayaVersions):
    system = platform.system()

    if system == 'Windows':

        import ctypes
        from ctypes.wintypes import MAX_PATH

        dll = ctypes.windll.shell32
        buf = ctypes.create_unicode_buffer(MAX_PATH + 1)
        if dll.SHGetSpecialFolderPathW(None, buf, 0x0005, False):
            mayaDir = os.path.join(buf.value, 'maya')
        else:
            print('Failed to resolve documents directory, falling back to Documents')
            mayaDir = os.path.expandvars(r'%USERPROFILE%\Documents\maya')

        envPathSep = ';'
    elif system == 'Darwin':
        mayaDir = os.path.expandvars(r'$HOME/Library/Preferences/Autodesk/maya')
        envPathSep = ':'
    else:
        mayaDir = os.path.expandvars(r'$HOME/maya')
        envPathSep = ':'

    if os.path.exists(mayaDir):
        for mayaVer in mayaVersions:
            maxVerDir = os.path.join(mayaDir, mayaVer)
            envConf = os.path.join(maxVerDir, 'Maya.env')
            if os.path.exists(envConf):

                if doInstall:
                    print('Registering plugin path for Maya {}'.format(mayaVer))
                    registerPlugin(envConf, envPathSep)
                else:
                    print('Unregistering plugin path for Maya {}'.format(mayaVer))
                    unregisterPlugin(envConf, envPathSep)

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_MAYA_VERSIONS:
            versions = [ver]
        else:
            print('Invalid or unsupported version:', ver)
            sys.exit(1)
    else:
        versions = SUPPORTED_MAYA_VERSIONS

    traverseMayaDirs(doInstall, versions)
