#!/usr/bin/env python3

import ctypes, os, pathlib, random, shutil, re, sys, winreg

SUPPORTED_MAX_VERSIONS = ['26.0', '27.0', '28.0', '29.0']

baseDir = os.path.dirname(os.path.abspath(__file__))

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

def traverseMaxDirs(doInstall, maxVersions):
    for maxVer in maxVersions:
        try:
            key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'SOFTWARE\\Autodesk\\3dsMax\\' + maxVer)
        except OSError:
            continue

        try:
            maxDir, _ =  winreg.QueryValueEx(key, 'Installdir')
        except OSError:
            continue

        # '24.0' -> '2022'
        dstDir = os.path.join(maxDir, 'Plugins')
        if os.path.exists(dstDir):
            dstFile = os.path.join(dstDir, 'verge3d.dle')
            if doInstall:
                print('Copy export menu plugin to {0}'.format(dstDir))
                maxVerHuman = str(int(float(maxVer)) + 1998)
                srcFile = os.path.join(baseDir, '..', '..', '..', 'max_plugin', 'exportMenu',
                                       maxVerHuman, 'verge3d.dle')
                shutil.copyfile(srcFile, dstFile)
            else:
                if os.path.exists(dstFile):
                    print('Remove export menu plugin from {0}'.format(dstDir))
                    os.remove(dstFile)

if __name__ == '__main__':
    if is_admin():
        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_MAX_VERSIONS:
                versions = [ver]
            else:
                print('Invalid or unsupported version:', ver)
                sys.exit(1)
        else:
            versions = SUPPORTED_MAX_VERSIONS

        traverseMaxDirs(doInstall, versions)
    else:
        print('Insufficient priviledges! Please run this script as admin!')
