# Target vault
$vaultName = "YOUR-VAULT-NAME"

# Connection details 
# authType 1 = Logged on windows user
# authType 2 = Windows user
# authType 3 = M-Files user
$authType = 1 
$userName = ""
$password = ""
$domain = ""
$spn = ""
$protocolSequence = "ncacn_ip_tcp"
$networkAddress = "localhost"
$endpoint = 2266
$encryptedConnection = $false
$localComputerName = ""


Write-Host "Connecting to vault..."

# Load M-Files API
$null = [System.Reflection.Assembly]::LoadWithPartialName("Interop.MFilesAPI")

# Connect to M-Files Server
$server = new-object MFilesAPI.MFilesServerApplicationClass
$tzi = new-object MFilesAPI.TimeZoneInformationClass
$tzi.LoadWithCurrentTimeZone()
$null = $server.ConnectAdministrativeEx( $tzi, $authType, $userName, $password, $domain, $spn, $protocolSequence, $networkAddress, $endpoint, $encryptedConnection, $localComputerName )

# Get the target vault
$vaultOnServer = $server.GetOnlineVaults().GetVaultByName( $vaultName )
if ($vaultOnServer -eq $null){
    return
}

# Login to vault
$vault = $vaultOnServer.LogIn()
if ($vault -eq $null){
    return
}

# Get application
$appGuid = "0c5ecf2d-7f21-4009-8270-bd5f3e3c8d51"
$app = $vault.CustomApplicationManagementOperations.GetCustomApplication($appGuid)
if ($app -eq $null){
    Write-Host "Extension Kit is not installed in specified vault."
    return
}

$version = $app.Version.ToString()
Write-Host "Current version of Extension Kit is $version."

# Set application version in NVS
$namespace = "Unitfly.ExtensionKit.VAF.VaultApplication"
[MFilesAPI.MFNamedValueType]$namedValueType = [MFilesAPI.MFNamedValueType]::MFSystemAdminConfiguration
[MFilesAPI.NamedValues] $namedValues = new-object MFilesAPI.NamedValuesClass
$namedValues["version"] = $version
$vault.NamedValueStorageOperations.SetNamedValues($namedValueType, $namespace, $namedValues)
Write-Host "Set version in Named value storage."
