##/******************************************************************************************
##Author                :     MohanRaj S
##Purpose               :     Display the License available in O365 and their License details
##Created               :     06/12/2017
##Modified By		    :     Prabaharan.T

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy

clear

$TestInputs=$args
$userName=$TestInputs[0]
$Password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUsr=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$RptnameProxyhost=($TestInputs[4]).ToString().Split("#")
$reportingNam=$RptnameProxyhost[0]
$proxyserverip=($RptnameProxyhost[1]).ToString().trim()
$azureVal=Eg-GetAzureEnv -UserName $userName
$azureEnvArr=$azureVal.Split(',')
if($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserverip.toString().toLower().Trim().Contains('none')) { $proxyserverip=$proxyserverip.toString().toLower().Trim() }

Try{
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $Password -asplaintext -force)

    if(!$proxyserverip.Contains('none')){
        $proxyserver='http://'+$proxyserverip
        [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
        if($proxyUsr -ne 'none' -and $proxyPass -ne 'none'){
            $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUsr, $(convertto-securestring $proxyPass -asplaintext -force)
            [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred   #[System.Net.CredentialCache]::DefaultNetworkCredentials
            [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
        }
     }



    Connect-MsolService -Credential $cred -AzureEnvironment $azureEnvArr[0]

    $subercnt = 0
    $msolaccnt = 0
    $rptPath='O365/'+$reportingNam

    #---------------START CMDLET------------------
    Try{
        $writmsolacc = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365msolAccsku" -keyFileName "kO365msolAccsku" -EgPath $egurkhaPath
        Get-MsolAccountSku |select AccountSkuID,SkuID,ActiveUnits,ConsumedUnits,WarningUnits |Export-Csv $writmsolacc[1]
        $null=Protect-File  $writmsolacc[1] -Algorithm AES -KeyAsPlainText $writmsolacc[0] -RemoveSource
    }Catch{
        $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	    Write-Error $exceptionmsg
    }

    $readmsolacc=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolAccsku" -keyFileName "kO365msolAccsku" -EgPath $egurkhaPath
    $unProtctMUsr=$readmsolacc[1] -replace (".csv",".dat") 
    $msolaccPath=Unprotect-File $unProtctMUsr -Algorithm AES -KeyAsPlainText $readmsolacc[0]	
    $MsolAccountSkus= import-csv $msolaccPath
    Remove-Item $msolaccPath

    Eg-DeleteFiles -FilePath $readmsolacc[2] -Pattern 'O365msolAccsku' -InputFile $readmsolacc[3]
    Eg-DeleteFiles -FilePath $readmsolacc[2] -Pattern 'kO365msolAccsku' -InputFile $readmsolacc[4]


    #---------------START CMDLET------------------
    Try{
        $writmsolsub = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365msolsub" -keyFileName "kO365msolsub" -EgPath $egurkhaPath
        Get-MsolSubscription |  select DateCreated,SkuId,OwnerObjectId,NextLifecycleDate,Status,IsTrial,TotalLicenses |Export-Csv $writmsolsub[1]
        $null=Protect-File  $writmsolsub[1] -Algorithm AES -KeyAsPlainText $writmsolsub[0] -RemoveSource
    }Catch{
        $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	    Write-Error $exceptionmsg
    }

    $readmsolsub=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolsub" -keyFileName "kO365msolsub" -EgPath $egurkhaPath
    $unProtctMUsr=$readmsolsub[1] -replace (".csv",".dat") 
    $msolsubPath=Unprotect-File $unProtctMUsr -Algorithm AES -KeyAsPlainText $readmsolsub[0]	
    $suber= import-csv $msolsubPath
    Remove-Item $msolsubPath

    Eg-DeleteFiles -FilePath $readmsolsub[2] -Pattern 'O365msolsub' -InputFile $readmsolsub[3]
    Eg-DeleteFiles -FilePath $readmsolsub[2] -Pattern 'kO365msolsub' -InputFile $readmsolsub[4]


    #---------------START CMDLET------------------
    <#
    Try{
        $writmsolLUsr = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365msolUsr" -keyFileName "kO365msolUsr" -EgPath $egurkhaPath
        Get-MsolUser -All |select IsLicensed,Licenses| ForEach-Object {$val=$_.Licenses.AccountSkuId -join '~';$_ | Add-Member -MemberType NoteProperty -Name 'AccId' -Value $val -PassThru} | Export-Csv -Path $writmsolLUsr[1]
        $null=Protect-File  $writmsolLUsr[1] -Algorithm AES -KeyAsPlainText $writmsolLUsr[0] -RemoveSource
    }Catch{Write-Host $_.Exception.Message}
    #>
    $readmsolLUsr=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolUsr" -keyFileName "kO365msolUsr" -EgPath $egurkhaPath
    $unProtctLUsr=$readmsolLUsr[1] -replace (".csv",".dat") 
    $mlUsrPath=Unprotect-File $unProtctLUsr -Algorithm AES -KeyAsPlainText $readmsolLUsr[0]	
    $mlicUser= import-csv $mlUsrPath
    Remove-Item $mlUsrPath

    Eg-DeleteFiles -FilePath $readmsolLUsr[2] -Pattern 'O365msolUsr' -InputFile $readmsolLUsr[3]
    Eg-DeleteFiles -FilePath $readmsolLUsr[2] -Pattern 'kO365msolUsr' -InputFile $readmsolLUsr[4]

    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"
    
    foreach($licnt in $MsolAccountSkus){
      $msolaccnt ++
    }
    

    foreach($cnt in $suber){
      $subercnt ++
    }
    $SubscrCount = $subercnt
    $LicCount = $msolaccnt
        for($i=0; $i -lt $LicCount; $i++){
            $AccountSkuID = $MsolAccountSkus[$i].AccountSkuID
            $SkuID = $MsolAccountSkus[$i].SkuID
            $LicUsers = $mlicUser | where {$_.IsLicensed -eq $True -and $_.AccId -like '*'+$AccountSkuID+'*'} | select IsLicensed
            $LicUsersCount = $LicUsers.Count
            if($LicUsers.Count -eq $null){
                $LicUsersCount=0
            }
        for($j=0; $j -lt $SubscrCount; $j++){
            $SubscrSKUID = $suber[$j].SkuID 
            if($SubscrSKUID -eq $SkuID){
                $ActiveUnits = $MsolAccountSkus[$i].ActiveUnits
                $ConsumedUnits = $MsolAccountSkus[$i].ConsumedUnits
                $WarningUnits = $MsolAccountSkus[$i].WarningUnits  
                $SubscrStatus= $suber[$j].Status
                $SubscrTrial = $suber[$j].IsTrial
                $SubscrTotal = $suber[$j].TotalLicenses
                $Subscrdate = $suber[$j].NextLifecycleDate
                if($Subscrdate -eq $null){
                    $Subscrdate=0
                }
                $ishavExpireDat= $false
                    if($Subscrdate -ne $null -and $Subscrdate -ne ''){
                        $ishavExpireDat=$true
                        $tempdate=$suber[$j].NextLifecycleDate
                        $cultInfo=(Get-Culture).Name
                        $StartDate = [DateTime]::ParseExact($tempdate,$DateTimeFormat,[cultureinfo]::GetCultureInfo($cultInfo),[System.Globalization.DateTimeStyles]::None)
                        $EndDate=(GET-DATE)
                        $DaysToExpireTmp = NEW-TIMESPAN –Start $EndDate –End $StartDate
                        $DaysToExpire=$DaysToExpireTmp.Days
                    }
              if($ishavExpireDat -eq $true){
                        Write-host 'AccountSkuID~'$AccountSkuID '~' $ActiveUnits '~' $ConsumedUnits '~' $WarningUnits '~' $LicUsersCount '~' $SubscrStatus '~' $SubscrTrial '~' $SubscrTotal '~' $Subscrdate '~' $DaysToExpire
                        Write-Host 'DDInformation~'$suber[$j].DateCreated '~' $suber[$j].SkuId '~' $suber[$j].OwnerObjectId
              }else{
                        Write-host 'AccountSkuID~'$AccountSkuID'~'$ActiveUnits '~' $ConsumedUnits '~' $WarningUnits '~' $LicUsersCount '~' $SubscrStatus '~' $SubscrTrial '~' $SubscrTotal '~' $Subscrdate '~' 'NIL'
                        Write-Host 'DDInformation~'$suber[$j].DateCreated '~' $suber[$j].SkuId '~' $suber[$j].OwnerObjectId
              }
        }
    }
}
}Catch{
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in Licene Usage Test --  $exceptionmsg"
}