Integrom.Module.Bootstrap.psm1

$dynamicEnumBlock = @"
   public enum %%ENUM_NAME%% {
      %%ENUM_DATA%%
   }
"@


$IntegromLibraryExtension = 'psil'

function getPossibleLibPaths{param([string]$libName, [string]$baseLibPath)
   [string[]]$pathSuffixes = '', '_lib\'
   [string[]]$result = @()

   if (-not [string]::IsNullOrEmpty($baseLibPath) -and -not ($baseLibPath -match '\\$')) {$baseLibPath = "$($baseLibPath)\"}
   
   $regexResult = [regex]::Match("$($baseLibPath)$($libName)", '(?<root>^[a-z]:|/|\.\.|\.|\\\\|(?:http|ftp|https|sftp)(://))?(?<path>.*(\\|/))?((?<libName>.+)(?<ext>\.psil$)|(?<libName>.+))', [Text.RegularExpressions.RegexOptions]::IgnoreCase)
   $root = $regexResult[0].Groups['root'].value
   $path = $regexResult[0].Groups['path'].value
   $libSname = $regexResult[0].Groups['libName'].value
   if ([string]::IsNullOrEmpty($root)) {$rootsToTest = '.\', '..\', "$($env:ProgramFiles)\Integrom\Libraries\"} else {$rootsToTest = $root}
   $pathSuffixes += "$($libSname)\"
   foreach ($rootEntry in $rootsToTest) {
      foreach ($pathSuffix in $pathSuffixes) {
         $result += "$($rootEntry)$($path)$($pathSuffix)$($libSname).$($IntegromLibraryExtension)"
      }
   }
   return $result
}

function loadLibraries {[CmdletBinding()]param([string[]]$libraryNames, [string]$libPath, [System.Management.Automation.PSCmdlet]$session)
   # [CmdletBinding()] is necessary to get the correct session state to load the library into
   if ($libraryNames.Count -lt 1) {return -5}

   [int]$statusCode = 0
   if ($null -eq $session) {$session = $PSCmdlet}
   foreach ($libraryName in $libraryNames) {
      Write-Host "Loading library $($libraryName)...."
      $success = $false
      foreach ($fqLibPath in (getPossibleLibPaths -libName $libraryName -baseLibPath $libPath)) {
         if (Test-Path $fqLibPath) {
            $rawLibCode = Get-Content -Path $fqLibPath -Raw
            $regexResult = [regex]::Match($rawLibCode, '^[\s|\t]*#_depends:[\s|\t]*(?<depends>.+)', [Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [Text.RegularExpressions.RegexOptions]::Multiline)
            $dependsRaw = $regexResult[0].Groups['depends'].value
            if (-not [string]::IsNullOrEmpty($dependsRaw)) {
               $dependsList = $dependsRaw -split ','
               foreach ($dependancy in $dependsList) {
                  loadLibraries ($dependancy.Trim()) $libPath $session
               }
            }
            $parsedLibCode = $rawLibCode -replace '%%PSIL_LOCATION%%', ($fqLibPath -replace '(?:\\|/)[^\\|/]+$', '')
            try {
               $ExecutionContext.SessionState.InvokeCommand.InvokeScript($session.SessionState, {param($libCode); Invoke-Expression -Command ($libCode)}.Ast.GetScriptBlock(), $parsedLibCode)
               $success = $true
               break
            } catch {
               break
            }
         }
      }
      if (-not $success) {
         $statusCode -= 1
      }
   }
   return $statusCode
}

function getLibraryVersion{param([string]$libraryName, [string]$libPath)
   foreach ($fqLibPath in (getPossibleLibPaths -libName $libraryName -baseLibPath $libPath)) {
      if (Test-Path $fqLibPath) {
         $rawLibCode = Get-Content -Path $fqLibPath -Raw
         $regexResult = [regex]::Match($rawLibCode, '^[\s|\t]*#_version:[\s|\t]*(?<version>[\w|.]+)', [Text.RegularExpressions.RegexOptions]::IgnoreCase -bor [Text.RegularExpressions.RegexOptions]::Multiline)
         return $regexResult[0].Groups['version'].value
      }
   }
   #$null = Invoke-Command {$fqLibPath} -NoNewScope
   return -1
}

function injectEnumFromJSON{[CmdletBinding()]param([string]$jsonFile, [string]$jsonKey, [string]$enumDef = $dynamicEnumBlock)
   # [CmdletBinding()] is necessary to get the correct session state to inject the Enum into
   [int]$v = 4001
   [scriptblock]$unboundCode = {param([string]$enumdef); Add-Type -TypeDefinition $enumdef}.Ast.GetScriptBlock()
   [PSCustomObject]$jsonFileData = Get-Content $jsonfile | ConvertFrom-Json
   if (($jsonFileData.$jsonKey).count -lt 1) {return -5}
   foreach ($item in $jsonFileData.$jsonKey) {$enumItems += "@$($item) = $($v),`n"; $v ++}
   $enumDef = $enumDef`
      -replace '%%ENUM_NAME%%', $jsonKey`
      -replace '%%ENUM_DATA%%', $enumItems
   try {
      $ExecutionContext.SessionState.InvokeCommand.InvokeScript($PSCmdlet.SessionState, $unboundCode, $enumDef)
      return 0
   } catch {
      return -17
   }
}