Set shell = CreateObject("Wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
scriptDir = fso.GetParentFolderName(WScript.ScriptFullName)
appRoot = fso.GetParentFolderName(scriptDir)
updateScript = scriptDir & "\check_and_update.ps1"
If Not fso.FileExists(appRoot & "\current_version.json") And fso.FolderExists("C:\QuarkVmwareClient") Then
    appRoot = "C:\QuarkVmwareClient"
End If

Function ResolveApiExe(rootPath)
    Dim exactPath, searchRoot, folder, file
    exactPath = rootPath & "\app\api\QuarkVmwareApi\QuarkVmwareApi.exe"
    If fso.FileExists(exactPath) Then
        ResolveApiExe = exactPath
        Exit Function
    End If
    searchRoot = rootPath & "\app\api"
    If fso.FolderExists(searchRoot) Then
        For Each folder In fso.GetFolder(searchRoot).SubFolders
            For Each file In folder.Files
                If LCase(file.Name) = "quarkvmwareapi.exe" Then
                    ResolveApiExe = file.Path
                    Exit Function
                End If
            Next
        Next
    End If
    ResolveApiExe = ""
End Function

apiExe = ResolveApiExe(appRoot)

If Not fso.FileExists(apiExe) Then
    MsgBox "API executable was not found:" & vbCrLf & apiExe, 16, "Startup Failed"
    WScript.Quit 1
End If

shell.Run "powershell.exe -ExecutionPolicy Bypass -File """ & updateScript & """ -AppRoot """ & appRoot & """ -Quiet", 0, True
apiExe = ResolveApiExe(appRoot)
shell.Run """" & apiExe & """", 0, False
