##/******************************************************************************************
##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]
$reprt=$TestInputs[4]
$rptndfrqcy=$reprt.split('#')
$reportingNam=$rptndfrqcy[0]
$showDD=$rptndfrqcy[1]
$proxyserverip=($rptndfrqcy[2]).ToString().trim()
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{

    $azureVal=Eg-GetAzureEnv -UserName $userName
    $azureEnvArr=$azureVal.Split(',')
     
    $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]
    $chkEnd=[datetime](Get-Date).AddDays(+5).ToUniversalTime()
    $chkStart=[datetime](Get-Date).ToUniversalTime()

    $dmnPwdExp=@{}
    $allowedcount = 0 
    $blockedcount = 0
    $TotalUsers = 0
    $licensecount = 0
    $enabledMFA = 0
    $disabledMFA = 0
    $enforcedMFA = 0
    $unlicensecount = 0
    $Passnevercount = 0
    $deletedcount = 0
    $nextexpiry = 0
    $rptPath='O365/'+$reportingNam
    #---------------START CMDLET------------------

    $readArr=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolUsr" -keyFileName "kO365msolUsr" -EgPath $egurkhaPath
    $unProtctMUsr=$readArr[1] -replace (".csv",".dat") 
    $musrPath=Unprotect-File $unProtctMUsr -Algorithm AES -KeyAsPlainText $readArr[0]	
    $usersview= import-csv $musrPath
    Remove-Item $musrPath

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

    #---------------START CMDLET------------------

    $delUsrRArr=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolDelUsr" -keyFileName "kO365msolDelUsr" -EgPath $egurkhaPath
    $unProtctMDUsr=$delUsrRArr[1] -replace (".csv",".dat") 
    $mdelusrPath=Unprotect-File $unProtctMDUsr -Algorithm AES -KeyAsPlainText $delUsrRArr[0]	
    $deluser= import-csv $mdelusrPath
    Remove-Item $mdelusrPath

    Eg-DeleteFiles -FilePath $delUsrRArr[2] -Pattern 'O365msolDelUsr' -InputFile $delUsrRArr[3]
    Eg-DeleteFiles -FilePath $delUsrRArr[2] -Pattern 'kO365msolDelUsr' -InputFile $delUsrRArr[4]


    #---------------START CMDLET------------------

    $dmUsrRArr=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolDomUsr" -keyFileName "kO365msolDomUsr" -EgPath $egurkhaPath
    $uPMDomUsr=$dmUsrRArr[1] -replace (".csv",".dat") 
    $mdomusrPath=Unprotect-File $uPMDomUsr -Algorithm AES -KeyAsPlainText $dmUsrRArr[0]	
    $domain= import-csv $mdomusrPath
    Remove-Item $mdomusrPath

    Eg-DeleteFiles -FilePath $dmUsrRArr[2] -Pattern 'O365msolDomUsr' -InputFile $dmUsrRArr[3]
    Eg-DeleteFiles -FilePath $dmUsrRArr[2] -Pattern 'kO365msolDomUsr' -InputFile $dmUsrRArr[4]


    #---------------START CMDLET------------------
    Try{
        $passPlcyWArr = Eg-WriteFile -ComntRptPath $rptPath -FileName "O365msolpass" -keyFileName "kO365msolpass" -EgPath $egurkhaPath  
        
        foreach($dmn in $domain){
            $valid=((Get-MsolPasswordPolicy -domain $dmn.Name -ErrorAction SilentlyContinue))| Select-Object -Property @{Name='Domain';Expression={$dmn.Name}},ValidityPeriod #|Export-Csv -Append -LiteralPath $passPlcyWArr[1] #-Force
            if($valid -ne $null -and $valid -ne ''){
                $valid|Export-Csv -Append -LiteralPath $passPlcyWArr[1] #-Force
            }
        }
        $null=Protect-File  $passPlcyWArr[1] -Algorithm AES -KeyAsPlainText $passPlcyWArr[0] -RemoveSource


    $passPlcyRArr=Eg-ReadFile -ComntRptPath $rptPath -FileName "O365msolpass" -keyFileName "kO365msolpass" -EgPath $egurkhaPath
    $mpassPlcyUsr=$passPlcyRArr[1] -replace (".csv",".dat") 
    $passPlcyPath=Unprotect-File $mpassPlcyUsr -Algorithm AES -KeyAsPlainText $passPlcyRArr[0]	
    $msolPassword= import-csv $passPlcyPath 
    for($j=0; $j -lt $msolPassword.Length; $j++){
        $Domain=$msolPassword[$j].Domain.toString()
        [int]$ValidityPeriod=$msolPassword[$j].ValidityPeriod
        $dmnPwdExp.Add($Domain,$ValidityPeriod)
    }
    Remove-Item $passPlcyPath

    Eg-DeleteFiles -FilePath $passPlcyRArr[2] -Pattern 'O365msolpass' -InputFile $passPlcyRArr[3]
    Eg-DeleteFiles -FilePath $passPlcyRArr[2] -Pattern 'kO365msolpass' -InputFile $passPlcyRArr[4]

    }Catch{
	  $egurkhaRprtPath=  $egurkhaPath+'\agent\'+$rptPath+'\'
          $fileRead=Get-ChildItem -Path $egurkhaRprtPath |Where-Object {$_.Name -like 'kO365msolpass*.dat'}| Sort-Object LastWriteTime -Descending | Select Name -First 1
            foreach($file in $fileRead){
                    $fileName=([String]$file.Name).Trim()
                    Remove-Item $egurkhaRprtPath$fileName -Force
            }
    }

    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $TimeFormat = $CultureDateTimeFormat.LongTimePattern
    $DateTimeFormat = "$DateFormat $TimeFormat"


    $TotalUsers=($usersview).Count
    $licensecount=($usersview|Where{$_.IsLicensed -eq $true}).Count
    $usersview=$usersview| Sort-Object UserPrincipalName 
    foreach($pwdexp in $usersview){
        if($pwdexp.PasswordNeverExpires -eq $true){
		if($Passnevercount -le $showDD){
	            Write-Host 'Passnever~'$pwdexp.UserPrincipalName'~'$pwdexp.SignInName'~'$pwdexp.AccId'~'$pwdexp.IsLicensed'~'$pwdexp.UsageLocation'!@!'
		}
	    $Passnevercount++
        }
        if($pwdexp.IsLicensed -ne $true){
		if($unlicensecount -le $showDD){
		   # if(-not  $pwdexp.UserPrincipalName.Contains('#EXT#')){
			Write-Host 'Unlicensed~'$pwdexp.UserPrincipalName'~'$pwdexp.DisplayName'~'"Unlicensed"'!@!'
		   # }
		}
        $unlicensecount++
        }
        if($pwdexp.BlockCredential -ne $true){
            $allowedcount++
        }else{
		if($blockedcount -le $showDD){
	            Write-Host 'blocked~'$pwdexp.UserPrincipalName'~'$pwdexp.SignInName'~'$pwdexp.AccId'~'$pwdexp.IsLicensed'~'$pwdexp.UsageLocation'!@!'
		}
	    $blockedcount++
        }

        #Mutli Factor Authenication
        if($pwdexp.MFAStatus -ne ''){
            if($pwdexp.MFAStatus -eq 'Enabled'){
                $enabledMFA++
                <#if($enabledMFA -le $showDD){
	                Write-Host 'MFAEnabled~'$pwdexp.UserPrincipalName'~!~'$pwdexp.SignInName'~!~-~!~'$pwdexp.UsageLocation'!@!'
		        }#>
            }
            elseif($pwdexp.MFAStatus -eq 'Enforced'){
                $enforcedMFA++
                <#if($enforcedMFA -le $showDD){
                    Write-Host 'MFAEnforced~'$pwdexp.UserPrincipalName'~!~'$pwdexp.SignInName'~!~-~!~'$pwdexp.UsageLocation'!@!'
                }#>
            }
		}
        else{
            $disabledMFA++
        }

    }

    foreach($deleteduser in $deluser){
	    if($deletedcount -le $showDD){
	        Write-Host 'usersdeleted~'$deleteduser.UserPrincipalName'~'$deleteduser.SignInName'~'$deleteduser.AccId'~'$deleteduser.IsLicensed'~'$deleteduser.UsageLocation'!@!'
	    }
	$deletedcount++
    }
    $users = $usersview |  where { $_.PasswordNeverExpires -eq $false } 
    $nextexpiry=0
    foreach($user in $users){
            $usrname = $user.UserPrincipalName
            $signname = $user.SignInName
            #[datetime]$passwordSetDate = $user.LastPasswordChangeTimestamp
            $passwordSetDate = [DateTime]::ParseExact($user.LastPasswordChangeTimestamp,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
            $domainName= $usrname.substring($usrname.IndexOf('@')+1)
            [int]$maxPasswordAge=$dmnPwdExp[$domainName]
            Try{
                $expireson = $passwordSetDate.addDays($maxPasswordAge)
                $expireson=$expireson.ToUniversalTime()
	            if(($chkStart -le $expireson) -and ($chkEnd -ge $expireson)){
	                $userlicAcc =  $user.AccId
	                $userislic = $user.IsLicensed
	                $usageloc = $user.UsageLocation
	                if($usageloc -eq $null){
			            $usageloc = "-"
	                }
	                if($userlicAcc -eq $null -or $userlicAcc -eq ''){
			            $userlicAcc = "-"
	                }
			    if($nextexpiry -le $showDD){
		            Write-Host 'userpassexpire~'$usrname'~'$signname'~'$expireson'~'$userlicAcc'~'$userislic'~'$usageloc'!@!'
			    }
                    $nextexpiry++
                }
            }Catch{}
        }
    }
    Catch{            
	Write-Host "Error Occured in O365UserLog -- " $_.Exception.Message        
	}

Write-Host 'unlicecnt~'$unlicensecount'!@!'
Write-Host 'deletedcount~' $deletedcount'!@!'
Write-Host 'Pwdnvrcnt~'$Passnevercount'!@!'
Write-Host 'signcount~'$allowedcount'~'$blockedcount'!@!'
Write-Host $(If ($nextexpiry.Equals(0)) {"nextexpire~-5"} Else {'nextexpire~'+$nextexpiry})'!@!'
Write-Host 'TotalUsers~'$TotalUsers'!@!'
Write-Host 'licecnt~'$licensecount'!@!'
Write-Host 'EnabledMFA~'$enabledMFA'!@!'
Write-Host 'EnforcedMFA~'$enforcedMFA'!@!'
Write-Host 'DisabledMFA~'$disabledMFA'!@!'