#Requires -Version 3.0
Function Backup-BrocadeSANSW {
<#
    .SYNOPSIS
            This function allows the backup of one or multiple Brocade SAN FC Switch
    .DESCRIPTION
            This function allows the backup of one or multiple Brocade SAN FC Switch on an FTP Server
    .PARAMETER  CSV
            The CSV file contains the list of all the IBM Brocade devices (Host / Username / Password)
            Backup-BrocadeSANSW.csv is used by default if nothing is specified
    .PARAMETER  ExportWithName
            This switch may be specified to format the output with the device's name rather than the host name
    .EXAMPLE
            Backup-BrocadeSANSW -CSV "e:\scripts\brocade_list.csv" -ExportWithName
            BackedUp Path                                                                        HostName      Device  
            -------- ----                                                                        --------      ------  
                True ftp://repository.katalykt.lan/SYSTEM/BROCADE2498/SW_FCA_20150612_105512.txt 192.168.16.100 SW_FCA
                True ftp://repository.katalykt.lan/SYSTEM/BROCADE2498/SW_FCB_20150612_105516.txt 192.168.16.101 SW_FCB
    .EXAMPLE
            Backup-BrocadeSANSW
            BackedUp Path                                                                                HostName      Device  
            -------- ----                                                                                --------      ------  
                True ftp://repository.katalykt.lan/SYSTEM/BROCADE2498/192.168.16.100_20150612_105532.txt 192.168.16.100 192.168.16.100
                True ftp://repository.katalykt.lan/SYSTEM/BROCADE2498/192.168.16.101_20150612_105536.txt 192.168.16.101 192.168.16.101
    .MODULES
            Posh-SSH
    .LINKS
            https://github.com/darkoperator/Posh-SSH
    .NOTES
            NAME:     Backup-BrocadeSANSW
            AUTHOR:   ROULEAU Benjamin
            LASTEDIT: 2015-06-12
            TESTED:   IBM Brocade 2498
#>
    #Requires -Module Posh-SSH
    [CmdletBinding()]
    PARAM(
        [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
        $CSV=(Join-Path -Path (Split-Path -parent $PSCommandPath) -ChildPath "Backup-BrocadeSANSW.csv"),
        
        [Switch]$ExportWithName
    )
    BEGIN {
        Write-Verbose -Message "[BEGIN Backup-BrocadeSANSW] Attempting to import the Posh-SSH Module..."
        # FTP Properties, our backup files will be stored in there
        $FTP_Host = "repository.katalykt.lan"
        $FTP_Username = "srv-backupop"
        $FTP_Password = "Passwd20160612"
        $FTP_Path = "SYSTEM/BROCADE2498"
    }
    PROCESS {
        # Retrieve the needed parameters for each given devices
        Import-Csv -Path $CSV -Delimiter ';' | ForEach-Object {
            $SSH_Username = $_.Username
            $SSH_Password = $_.Password
            $SSH_Host = $_.Host
            $IsBackedUp = $false
            # Build up the Credentials
            $SSH_Password = ConvertTo-SecureString $SSH_Password -AsPlainText -Force
            $SSH_Credentials =  New-Object System.Management.Automation.PSCredential ($SSH_Username, $SSH_Password)
            Write-Verbose -Message "[PROCESS Backup-BrocadeSANSW] Processing SSH Host: $SSH_Host"
            # Attempt to start an SSH Session
            TRY {
                Write-Verbose -Message "[PROCESS Backup-BrocadeSANSW] Attempting to connect to the SSH Host: $SSH_Host"
                $SSH_Session = New-SSHSession -ComputerName $SSH_Host -Credential $SSH_Credentials -AcceptKey $true -ErrorAction Stop
            } CATCH {
                Write-Warning -Message "[PROCESS Backup-BrocadeSANSW] Unable to start an SSH Session on the given host"
                $SSH_Session = $false
            }
            # Ensure that the SSH Session is alive and kicking
            IF ($SSH_Session) {
                # By default, we use the SSH Host as a label
                $SSH_DeviceName = $SSH_Host
                # Retrieve the SSH Device Name if specified
                IF ($ExportWithName) {
                    Write-Verbose -Message "[PROCESS Backup-BrocadeSANSW] Attempting to retrieve the device name"
                    $SSH_DeviceName = Invoke-SSHCommand -SSHSession $SSH_Session -Command "switchshow | grep switchName"
                    $SSH_DeviceName = $SSH_DeviceName.Output -match "\:\s(.*[a-zA-Z0-9])"
                    $SSH_DeviceName = $matches[1]
                    IF (-not($SSH_DeviceName)) {
                        Write-Warning -Message "[PROCESS Backup-BrocadeSANSW] Unable to retrieve the Device Name, falling back to the Host name"
                        $SSH_DeviceName = $SSH_Host
                    }
                    Write-Verbose -Message "[PROCESS Backup-BrocadeSANSW] Retrieved device name: '$SSH_DeviceName'"
                }
                # Export the Log to the FTP
                $FTP_ExportFullPath = "{0}/{1}_{2}.txt" -f $FTP_Path, $SSH_DeviceName, (Get-Date -Format "yyyyMMdd_HHmmss")
                $SSH_Export = Invoke-SSHCommand -SSHSession $SSH_Session -Command ("configupload -all -p ftp {0},{1},{2},{3}" -f $FTP_Host, $FTP_Username, $FTP_ExportFullPath, $FTP_Password)
                # Make sure that the output match the expected valid return
                IF ($SSH_Export.Output -like "*All selected config parameters are uploaded*") {
                    Write-Verbose -Message "[PROCESS Backup-DevicesConfiguration] Device '$SSH_DeviceName' configuration has been backed up"
                    # Append the FTP host to the path for the output
                    $FTP_ExportFullPath = "ftp://{0}" -f ((Join-Path $FTP_Host -ChildPath $FTP_ExportFullPath) -replace '\\','/')
                    $IsBackedUp = $true
                } ELSE {
                    Write-Warning -Message "[PROCESS Backup-DevicesConfiguration] Failed to back up device '$SSH_DeviceName': $($SSH_Export.Output)"
                    $FTP_ExportFullPath = "Failed"
                }
                # Remove the SSH Session
                $SSH_Session | Remove-SSHSession | Out-Null
                # Return the Output
                New-Object -TypeName PSObject -Property @{
                    Device = $SSH_DeviceName
                    HostName = $SSH_Host
                    BackedUp = $IsBackedUp
                    Path = $FTP_ExportFullPath
                }
            }
        }
    }
    END {
    }
}