[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
$reportingname='EXO/'+$TestInputs[0]
$userName=$TestInputs[1]
$Password=Eg-O365Dcr -EncStr $TestInputs[2]
$proxyids=$TestInputs[3]
$days=$TestInputs[4]
$prxyusrpwd=$proxyids.split("#")
$alldays=$days.split("#")
$proxyUsr=$prxyusrpwd[0]
$proxyPass=Eg-O365Dcr -EncStr $prxyusrpwd[1]
$activeDays=$alldays[0]
$InactiveDays=$alldays[1]
$PassExpDays=$alldays[2]
$ExcludingNames=$alldays[3]
$proxyserverip=($alldays[4]).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() }

$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]

$readfiles=0
$readfiles1=0
$readfiles2=0
$readfiles3=0
$dmnPwdExp=@{}

try{  
    $readfiles=Eg-ReadFile -ComntRptPath $reportingname -FileName "mailbox" -keyFileName "kmailbox" -EgPath $egurkhaPath
    $datafile=$readfiles[1] -replace (".csv",".dat") 
    $csvfile=Unprotect-File $datafile -Algorithm AES -KeyAsPlainText $readfiles[0]	
    $measureterms= import-csv $csvfile
    Remove-Item $csvfile
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'mailbox' -InputFile $readfiles[3]
    Eg-DeleteFiles -FilePath $readfiles[2] -Pattern 'kmailbox' -InputFile $readfiles[4]
}
catch [System.Management.Automation.RuntimeException] {
    Write-Error -Message "File not found. The $reportingname location does not contain mailbox files."
}
catch{
    $errmsg=$_.Exception.Message
    $errstack=$_.Exception.StackTrace
    Write-Error -Message $errmsg
}

try{
    $readfiles1=Eg-ReadFile -ComntRptPath $reportingname -FileName "casmailboxes" -keyFileName "kcasmailboxes" -EgPath $egurkhaPath
    $datafile1=$readfiles1[1] -replace (".csv",".dat") 
    $csvfile1=Unprotect-File $datafile1 -Algorithm AES -KeyAsPlainText $readfiles1[0]	
    $DDD= import-csv $csvfile1
    Remove-Item $csvfile1
    Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'casmailboxes' -InputFile $readfiles1[3]
    Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'kcasmailboxes' -InputFile $readfiles1[4]
}
catch [System.Management.Automation.RuntimeException] {
    Write-Error -Message "File not found. The $reportingname location does not contain casmailboxes files."
}
catch{
    $errmsg=$_.Exception.Message
    $errstack=$_.Exception.StackTrace
    Write-Error -Message $errmsg
}

try{
    $readfiles2=Eg-ReadFile -ComntRptPath $reportingname -FileName "statsmailbox" -keyFileName "kstatsmailbox" -EgPath $egurkhaPath
    $datafile2=$readfiles2[1] -replace (".csv",".dat") 
    $csvfile2=Unprotect-File $datafile2 -Algorithm AES -KeyAsPlainText $readfiles2[0]	
    $mailboxstatistics= import-csv $csvfile2
    Remove-Item $csvfile2
    Eg-DeleteFiles -FilePath $readfiles2[2] -Pattern 'statsMailbox' -InputFile $readfiles2[3]
    Eg-DeleteFiles -FilePath $readfiles2[2] -Pattern 'kstatsMailbox' -InputFile $readfiles2[4]
	$mailStats=$mailboxstatistics | select -First 1
	#$isPreviousScript=[bool]($mailStats.PSobject.Properties.name -match "PrimarySmtpAddress")
}
catch [System.Management.Automation.RuntimeException] {
    Write-Error -Message "File not found. The $reportingname location does not contain statsmailbox files."
}
catch{
    $errmsg=$_.Exception.Message
    $errstack=$_.Exception.StackTrace
    Write-Error -Message $errmsg
}

try{
    $readfiles3=Eg-ReadFile -ComntRptPath $reportingname -FileName "RecipntPerm" -keyFileName "kRecipntPerm" -EgPath $egurkhaPath
    $datafile3=$readfiles3[1] -replace (".csv",".dat") 
    $csvfile3=Unprotect-File $datafile3 -Algorithm AES -KeyAsPlainText $readfiles3[0]	
    $ReciPrmterm= import-csv $csvfile3
    Remove-Item $csvfile3
    Eg-DeleteFiles -FilePath $readfiles3[2] -Pattern 'RecipntPerm' -InputFile $readfiles3[3]
    Eg-DeleteFiles -FilePath $readfiles3[2] -Pattern 'kRecipntPerm' -InputFile $readfiles3[4]
}
catch [System.Management.Automation.RuntimeException] {
    Write-Error -Message "File not found. The $reportingname location does not contain RecipntPerm files."
}
catch{
    $errmsg=$_.Exception.Message
    $errstack=$_.Exception.StackTrace
    Write-Error -Message $errmsg
}
 
Try{
    $dmUsrWArr = Eg-WriteFile -ComntRptPath $reportingname -FileName "O365msolDomUsr" -keyFileName "kO365msolDomUsr" -EgPath $egurkhaPath
    Get-MSOLDomain | select * |Export-Csv $dmUsrWArr[1]
    $null=Protect-File  $dmUsrWArr[1] -Algorithm AES -KeyAsPlainText $dmUsrWArr[0] -RemoveSource
}Catch{}

$dmUsrRArr=Eg-ReadFile -ComntRptPath $reportingname -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]

Try{
	$passPlcyWArr = Eg-WriteFile -ComntRptPath $reportingname -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
	    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 $reportingname -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
        }
    }
    Try{
        $writArr = Eg-WriteFile -ComntRptPath $reportingname -FileName "O365msolUsr" -keyFileName "kO365msolUsr" -EgPath $egurkhaPath
        Get-MsolUser -All| select * |Export-Csv $writArr[1]
        $null=Protect-File  $writArr[1] -Algorithm AES -KeyAsPlainText $writArr[0] -RemoveSource
    }Catch{}

    $readArr=Eg-ReadFile -ComntRptPath $reportingname -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]

    Write-Host 'ReadFile:'$readfiles[3]','$readfiles1[3] ','$readfiles2[3] ','$readfiles3[3] ','$readArr[3] ','$dmUsrRArr[3]
	$sysDat=Get-Date
	$MsolRole = Get-MsolRole
	foreach($roles in $MsolRole){
	    $rolemember=Get-MsolRoleMember -RoleObjectId $roles.ObjectId |Where{$_.RoleMemberType -eq 'User'}|select DisplayName
        if($rolemember -ne $null){
		foreach($rolemembers in $rolemember ){   
                Write-Host 'DDAdminUsers' $rolemembers.DisplayName '!' $roles.Name 
		    }
	    }
	} 
    
    $actSync=0
	$actNonSync=0
	$ExcludingNames=$ExcludingNames.Replace("_"," ")
	$ExcludingName=$ExcludingNames.split('|')
	$DDD=$DDD |where {$ExcludingName -notcontains $_.DisplayName} | Sort-Object DisplayName 
    
    $culture = Get-Culture
    $culture.DateTimeFormat.ShortDatePattern = 'yyyy-MM-dd'
    Set-Culture $culture
    $CultureDateTimeFormat = (Get-Culture).DateTimeFormat
    $DateFormat = $CultureDateTimeFormat.ShortDatePattern
    $DateTimeFormat = "$DateFormat"
    <#
    if($isPreviousScript){
	    foreach($Measures in $DDD){
            try{
                if($Measures.ActiveSyncEnabled -ne $true){
                    $LastLogonTime=$mailboxstatistics |  Where-Object {$_.PrimarySmtpAddress -eq $Measures.PrimarySmtpAddress} | select LastLogonTime
                    $usrLogonDat = [DateTime]::ParseExact($LastLogonTime.LastLogonTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
	                Write-Host DDSyncUsers $Measures.PrimarySmtpAddress '~!~'$usrLogonDat '~!~-~!~-~!~-~!~-'
                    $actNonSync++
                }
                else{
                    $actSync++
                }
            }catch{
                if($Measures.ActiveSyncEnabled -ne $true){
                    $LastLogonTime=$mailboxstatistics |  Where-Object {$_.PrimarySmtpAddress -eq $Measures.PrimarySmtpAddress} | select LastLogonTime
                    $usrLogonDat = [DateTime]::ParseExact($LastLogonTime.LastLogonTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)	            
	                Write-Host DDSyncUsers $Measures.PrimarySmtpAddress '~!~'$usrLogonDat '~!~-~!~-~!~-~!~-'
                    $actNonSync++
                }
                else{
                    $actSync++
                }
            }
        }
        $lastsyncUsers=$mailboxstatistics | Sort-Object { $_.LastLogonTime -as [DateTime] } -Descending | select -First 10
        foreach($topActiveUsers in  $lastsyncUsers  ){
            $usrLogonDat = [DateTime]::ParseExact($topActiveUsers.LastLogonTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
            Write-Host DDActiveSyncUsers $topActiveUsers.PrimarySmtpAddress ~!~ $usrLogonDat
        }
    }
    #>
    #else{
	    foreach($Measures in $DDD){
            try{
                if($Measures.ActiveSyncEnabled -ne $true){
                    $LastLogonTime=$mailboxstatistics |  Where-Object {$_.UserPrincipalName -eq $Measures.PrimarySmtpAddress} | select LastActivityDate
                    $usrLogonDat = [DateTime]::ParseExact($LastLogonTime.LastActivityDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
	                Write-Host DDSyncUsers $Measures.PrimarySmtpAddress '~!~'$usrLogonDat '~!~-~!~-~!~-~!~-'
                    $actNonSync++
                }
                else{
                    $actSync++
                }
            }catch{
                if($Measures.ActiveSyncEnabled -ne $true){
                    $LastLogonTime=$mailboxstatistics |  Where-Object {$_.UserPrincipalName -eq $Measures.PrimarySmtpAddress} | select LastActivityDate
                    $usrLogonDat = [DateTime]::ParseExact($LastLogonTime.LastActivityDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)	            
	                Write-Host DDSyncUsers $Measures.PrimarySmtpAddress '~!~'$usrLogonDat '~!~-~!~-~!~-~!~-'
                    $actNonSync++
                }
                else{
                    $actSync++
                }
            }
        }
        $lastsyncUsers=$mailboxstatistics | Sort-Object { $_.LastActivityDate -as [DateTime] } -Descending | select -First 10
        foreach($topActiveUsers in  $lastsyncUsers  ){
            $usrLogonDat = [DateTime]::ParseExact($topActiveUsers.LastActivityDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
            Write-Host DDActiveSyncUsers $topActiveUsers.UserPrincipalName ~!~ $usrLogonDat
        }  
    #}
	Write-Host  SyncUsers$actSync'#'$actNonSync
    $ReciPrmterm=$ReciPrmterm | Sort-Object Identity
    foreach($mm in $ReciPrmterm){
	    if($mm -ne $null){
	    write-host SendAs $mm.Identity'~!~'$mm.Trustee'~!~'$mm.AccessControlType'~!~'$mm.IsInherited'~!~'$mm.InheritanceType'~!~'$mm.IsValid
	    }
	}

	$SendOnBehalf=$measureterms |  Where-Object {$_.GrantSendOnBehalfTo -ne ''} | select DisplayName,Alias,UserPrincipalName,PrimarySmtpAddress,GrantSendOnBehalfTo,Identity | Sort-Object Identity
	foreach($mailbox in $SendOnBehalf){	
		Write-Host SendOnBehalf  $mailbox.DisplayName'~!~'$mailbox.UserPrincipalName'~!~'$mailbox.PrimarySmtpAddress'~!~'$mailbox.GrantSendOnBehalfTo'~!~-~!~-'
	}

	$Activecount=0 
	$InActivecount=0
	$neverlogcount=0
    <#
	if($isPreviousScript){
	    Foreach ($mailboxstat in $mailboxstatistics) {           
	        if($mailboxstat.LastLogonTime -eq $null -or $mailboxstat.LastLogonTime -eq "" ){
		        if($mailboxstat.DisplayName -ne "Discovery Search Mailbox"){
		            Write-Host "NeverLoggedIn~"$mailboxstat.PrimarySmtpAddress'~!~-~!~-~!~-~!~-~!~-'
		            $neverlogcount++
		        }
	        }
	        else{
	            #[datetime]$usrLogonDat=$mailboxstat.LastLogonTime
                $usrLogonDat = [DateTime]::ParseExact($mailboxstat.LastLogonTime,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
		        if($usrLogonDat -gt  $sysDat.AddDays(-$activeDays)){
				    #Write-Host "Active users~"$mailboxstat.PrimarySmtpAddress'~!~'$usrLogonDat '~!~-~!~-~!~-~!~-'
		            $Activecount++
			    }
			    elseif($usrLogonDat -lt $sysDat.AddDays(-$InactiveDays)){
				    Write-Host "Inactive users~"$mailboxstat.PrimarySmtpAddress'~!~'$usrLogonDat'~!~-~!~-~!~-~!~-'
		            $InActivecount++
			    }
	        }
	    }
    }
    #>
    #else{
        Foreach ($mailboxstat in $mailboxstatistics){           
	        if($mailboxstat.LastActivityDate -eq $null -or $mailboxstat.LastActivityDate -eq "" ){
		        if($mailboxstat.DisplayName -ne "Discovery Search Mailbox"){  
		            Write-Host "NeverLoggedIn~"$mailboxstat.UserPrincipalName'~!~-~!~-~!~-~!~-~!~-'
		            $neverlogcount++
		        }
	        }
	        else{
                $usrLogonDat = [DateTime]::ParseExact($mailboxstat.LastActivityDate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
		        if ($usrLogonDat -gt  $sysDat.AddDays(-$activeDays)){
		            $Activecount++
			    }
			    elseif($usrLogonDat -lt $sysDat.AddDays(-$InactiveDays)){
				    Write-Host "Inactive users~"$mailboxstat.UserPrincipalName'~!~'$usrLogonDat'~!~-~!~-~!~-~!~-'
		            $InActivecount++
			    }
	        }
	    }
    #}
    $cultureDTFrmt1 = Get-Culture
    $cultureDTFrmt1.DateTimeFormat.ShortDatePattern = 'M/d/yyyy'
    $cultureDTFrmt1.DateTimeFormat.LongTimePattern='h:mm:ss tt'
    Set-Culture $cultureDTFrmt1
    $CultureDateTimeFormat1 = (Get-Culture).DateTimeFormat
    $DateFormat1 = $CultureDateTimeFormat1.ShortDatePattern
    $TimeFormat1 = $CultureDateTimeFormat1.LongTimePattern
    $DateTimeFormat1 = "$DateFormat1 $TimeFormat1"
	$users = $usersview |  where { $_.PasswordNeverExpires -eq $false } 
	$chkEnd=[datetime](Get-Date).AddDays(+$PassExpDays).ToUniversalTime()
	$chkStart=[datetime](Get-Date).ToUniversalTime()
	foreach($user in $users){
        $usrname = $user.UserPrincipalName
        $signname = $user.SignInName
        #[datetime]$passwordSetDate = $user.LastPasswordChangeTimestamp 
        $passwordSetDate = [DateTime]::ParseExact($user.LastPasswordChangeTimestamp,$DateTimeFormat1,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
        $domainName= $usrname.substring($usrname.IndexOf('@')+1)
        [int]$maxPasswordAge=$dmnPwdExp[$domainName]
        try{
	        $expireson = $passwordSetDate.addDays($maxPasswordAge)
            if(($chkStart -le $expireson) -and ($chkEnd -ge $expireson)){
                $userlicAcc =  $user.Licenses.AccountSKUID
                if($userlicAcc -eq $null){
                    $userlicAcc = "-"
                }
                $userislic = $user.IsLicensed
                $usageloc = $user.UsageLocation
                if($usageloc -eq $null){
                    $usageloc = "-"
                }
                Write-Host 'userpassexpire~'$usrname'~!~'$signname'~!~'$expireson'~!~'$userlicAcc'~!~'$userislic'~!~'$usageloc
            }
        }
        catch{}
    }
Write-Host 'UsersCount~'$Activecount'~'$InActivecount'~'$neverlogcount