session.psm1



$sDir = "$env:LOCALAPPDATA/.ps"
$zPath = "$sDir/x.data"

Add-Type -assembly "system.io.compression.filesystem"

.(commonLib) 

function CreateXtremSessionObject() {
    $SessionObject = @{
        _XtremUsername = "test"
        _XtremPassword = $null
        _XtremName = $null
        _alias = $null
        _XtremClusterName = $null
        _XtremCLIMode = $true
        _XtremDefaultCluster = $null
        _XtremClusterTypeByName = @{}
        _XtremClusterTypeByIndex = @{}
        _XtremClustersTable = @{}
        _XMSversion = $null
    }

    $SessionObject = Create-XtremClusterFunctions($SessionObject)
    return $SessionObject
}
#Defines global username, password, and hostname/ip for PS session
function New-XtremSession() {
  <#
     .DESCRIPTION
      Defines global variables (IP/hostname, username, and password) so they do not have to be explicitly defined for subsequent calls.
      If you do not define any switches, New-XtremSession will prompt you for credentials. This is best for an interactive session.
      When automating, it is best to run with switches at the beginning of scripts - I.E New-XtremSession -xioname name -username name -password pw.
      This will not prompt, and you can run other functions further down your script without explicitly sending credential arguments.
 
      .PARAMETER XmsName
      IP Address or hostname for XtremIO XMS. Optional if interactive prompts
 
      .PARAMETER xmsAlias
      Short name for XtremIO XMS. For better look in prompt and selection lists.
 
      .PARAMETER XtremClusterName
      Name of the XtremIO you are sending the command to. This is new in 4.0 as XMS can manage multiple systems
 
      .PARAMETER Username
      Username for XtremIO XMS. Optional if interactive prompts
 
      .PARAMETER Password
      Password for XtremIO XMS. Optional if interactive prompts
 
      .PARAMETER Credential
      Providing PSCredential object instead of a user/password.
 
      .PARAMETER CLIMode
      Declare the sesson is interactive and provide confirmations for remove operations. set to false to ignore interactive mode.
 
      .EXAMPLE
      New-XtremSession
 
      .EXAMPLE
      New-XtremSession -XmsName 10.4.45.24 -XtremClusterName cluster01 -Username admin -Password password123 -xmsAlias XMS-1579
  #>

    [cmdletbinding()]
    [Alias('xmsSessionCreate')]
    Param(
    [Parameter(Mandatory=$true)]
    [string]$XmsName,
    [Parameter()]
    [string]$xmsAlias,
    [Parameter()]
    [string]$Username,
    [Parameter()]
    [string]$Password,
    [Parameter()]
    [PSCredential]$Credential=$null,
    [Parameter()]
    [bool]$CLIMode=$true,
    [Parameter()]
    [string]$XtremClusterName
    )

    Set-XtremTrustAllCertsPolicy

    $SessionObject = CreateXtremSessionObject

    #for interactive session
    if (!$XmsName){
        $SessionObject._XtremName = Read-Host -Prompt "Enter XtremIO XMS Hostname or IP Address"
    }
    if (!$XtremClusterName){
        $SessionObject._XtremClusterName = Read-Host -Prompt "Enter XtremIO Cluster name (Optional)"
    }
    if (!$Username -and !$Credential.UserName) {
        $SessionObject._XtremUsername = Read-Host -Prompt "Enter XtremIO username"
    }
    if (!$Password -and !$Credential.Password) {
        $SessionObject._XtremPassword = Read-Host -Prompt "Enter password" -AsSecureString
    }

    $SessionObject._XtremClusterName = $XtremClusterName
    $SessionObject._XtremName = $XmsName

    if ($Credential -ne $null) {
        $SessionObject._XtremUsername = $Credential.UserName
        $SessionObject._XtremPassword = $Credential.Password
    } else {
        $SessionObject._XtremUsername = $Username
        $securepassword = ConvertTo-SecureString $password -AsPlainText -Force
        $SessionObject._XtremPassword =$securepassword
    }
    $SessionObject._XtremCLIMode = $CLIMode
    if(!$xmsAlias){
        $xmsAlias = $XmsName
    }
    $SessionObject._alias = $xmsAlias
        


    $global:XtremDefaultSessionObject = $SessionObject

    $cls = Get-XtremClusters
    foreach ($cl in $cls) {
        if ($cl.index -and $cl.name) {
            $n = $cl.index
            $SessionObject._XtremClustersTable["$n"] = $cl.name
        }
    }
    $SessionObject._XtremClustersTable = [PSCustomObject]$SessionObject._XtremClustersTable

    try {
        $XMS = Get-XtremXMS
        $XMSVersion = $XMS.version.Split(".");
        if ($XMSVersion[0] -lt 4) {
            $global:XtremDefaultSessionObject = $null
            throw "XMS version is less then 4.0.0. XtremLib only supports 4.0.0 an above."
        }
        $SessionObject._XMSversion = $XMSVersion
        $SessionObject.SetXtremInternalPopulateClusters()

    } catch {
        $global:XtremDefaultSessionObject = $null
        throw "Could not retrieve XMS data from XMS Server, or XMS is less then 4.0.0."
    }  

    $saveSessionKey = $XtremDefaultSessionObject._alias
    $saveSessionBody = $XtremDefaultSessionObject
    saveXtremSession ($saveSessionKey)($saveSessionBody)
}

function Remove-XtremSession {
  <#
    .DESCRIPTION
    Removes saved session. Use [TAB] or [Ctrl]+[Space] to view and select saved values.
 
    .PARAMETER selectedSessionName
    Name of the session to delete.
 
    .EXAMPLE
    Remove-XtremSession selectedSessionName
  #>

    [cmdletbinding()]
    [Alias('xmsSessionRemove')]
    Param(
        [Parameter(Mandatory = $true)]
        [Argumentcompleter( { fillFunc 'completeSessions' $args })] 
        [string]$selectedSessionName
    )

    if ([System.IO.File]::Exists($zPath)) {
        readSessions
        if($global:AllXtremSessions[$selectedSessionName]){
            $global:AllXtremSessions.remove("$selectedSessionName")
            saveSessions
            removeFile
        }else{
            Write-Host "No session named $selectedSessionName" -ForegroundColor Red
        }
    }
    else {
        Write-Host "No current session. Please call New-XtremSession command to create one." -ForegroundColor Magenta
    }
}

function Get-XtremDefaultSession {
    if (!$XtremDefaultSessionObject) {
        if ([System.IO.File]::Exists($zPath)) {
            # Write-Host "No current session. Loading the previous: " -NoNewline -ForegroundColor Magenta
            # Select-XtremSession
            readSessions
            $kArr = $AllXtremSessions.keys
            $selectedSessionName = ($kArr.GetEnumerator() | Select-Object -first 1)
            Set-XtremTrustAllCertsPolicy
            $SessionObject = $AllXtremSessions[$selectedSessionName]
            $global:XtremDefaultSessionObject = Create-XtremClusterFunctions($SessionObject)
        }
        else {
            Write-Host "No current session. Please call New-XtremSession command to create one." -ForegroundColor Magenta
        }
    }
    return $XtremDefaultSessionObject
}

function Select-XtremSession {
    <#
    .DESCRIPTION
    Select a previously saved sessions. Use [TAB] to circle or [Ctrl]+[Space] to view values.
     
    .PARAMETER selectedSessionName
    Name of the session.
     
    .EXAMPLE
    Select-XtremSession selectedSessionName
  #>

    [cmdletbinding()]
    [Alias('sxs', 'xmsSessionSelect')]
    Param(
        [Parameter(Mandatory = $true)]       
        [Argumentcompleter( { ' '; (New-Object -ComObject wscript.shell).SendKeys('{backspace}{tab}') })]
        [string] $selectedSessionName
    )
        
    if ([System.IO.File]::Exists($zPath)) {
        readSessions
        if($global:AllXtremSessions[$selectedSessionName]){
            
            saveXtremSession ($selectedSessionName)($global:AllXtremSessions[$selectedSessionName])
            
            # Write-Host "$selectedSessionName" -ForegroundColor Cyan
            Set-XtremTrustAllCertsPolicy
            $SessionObject= $global:AllXtremSessions[$selectedSessionName]
            $global:XtremDefaultSessionObject = Create-XtremClusterFunctions($SessionObject)
        }else{
            Write-Host "No session named $selectedSessionName" -ForegroundColor Red
        }
    }else{
        Write-Host "No current session. Please call New-XtremSession command to create one." -ForegroundColor Magenta
    }
}

Register-ArgumentCompleter -Command Select-XtremSession -Param selectedSessionName -ScriptBlock { fillFunc 'completeSessions' $args }

function Select-XtremCluster() {
    <#
    .DESCRIPTION
    Select a cluster in multicluster XMS. Use [TAB] to circle or [Ctrl]+[Space] to view values.
     
    .PARAMETER selectedClusterName
    Name of the session.
     
    .EXAMPLE
    Select-XtremCluster selectedClusterName
  #>

    [cmdletbinding()]
    [Alias('sxc', 'xmsSessionSelectCluster')]
    Param(
        [Parameter(Mandatory = $true)]
        [Argumentcompleter( { fillFunc 'completeSessionClusters' $args })] 
        [string]$selectedClusterName
    )
        
    if ([System.IO.File]::Exists($zPath)) {
        readSessions
        if ($global:XtremDefaultSessionObject) {
            $session = $XtremDefaultSessionObject._alias
            $XtremDefaultSessionObject._XtremClustersTable.psobject.properties | ForEach-Object { 
                if ($_.value -eq $selectedClusterName) { 
                    $selectedClusterIndex = $_.name 
                } 
            }
                # $ht = [hashtable]$XtremDefaultSessionObject._XtremClustersTable
                # Foreach ($item in ($ht.GetEnumerator() | Where-Object { $_.Value -eq $selectedClusterName }))
                # { $selectedClusterIndex = $item.name }


            if ($selectedClusterIndex){
                $XtremDefaultSessionObject._XtremClusterName = $selectedClusterName
                $XtremDefaultSessionObject._XtremDefaultCluster = $selectedClusterIndex
                    
                saveXtremSession ($session)($XtremDefaultSessionObject)
            }

        } else {
            Write-Host 'No session selected. Use Select-XtremSession or New-XtremSession command.' -ForegroundColor Red
        }
    }
    else {
        Write-Host 'No current session. Please call New-XtremSession command to create one.' -ForegroundColor Magenta
    }
}

function Exit-XtremSession(){
    <#
    .DESCRIPTION
    Clears the globally set credentials or the current session. Custom XtremIO prompt replaced with the normal. Takes no arguments
 
    .EXAMPLE
    Exit-XtremSession
  #>

    [cmdletbinding()]
    [Alias('xmsSessionExit')]
    Param()
    $global:XtremDefaultSessionObject = $null
}

$global:initialWinTitle = ''
function global:prompt {
    
    if ($XtremDefaultSessionObject) {
        if (!$initialWinTitle) {
            $global:initialWinTitle = [Console]::Title
        }
        $clusterName = $XtremDefaultSessionObject._XtremClusterName
        $theTitle = " XMS: $($XtremDefaultSessionObject._XtremName)"
        if($clusterName){
            $theTitle += " Cluster: $clusterName"
            $thePromptCluster = " $clusterName"
        }
        [Console]::Title = $theTitle
        Write-Host -Object "[$($XtremDefaultSessionObject._alias)]$thePromptCluster" -NoNewline -ForegroundColor DarkGreen
        return '> '
    }
    else {
        if ($initialWinTitle) {
            [Console]::Title = $initialWinTitle
            $initialWinTitle = ''
        }
        "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1)) ";
    }
}


Export-ModuleMember *-* -Alias *