<#
    /*****************************************************************************
    Author            :       Prabaharan.T
    Purpose           :       used to get the site information from SPO site collections
    Created           :       31/01/2018
    Modified By       : 

#>
[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 -WarningAction SilentlyContinue
clear
Set-ExecutionPolicy -ExecutionPolicy Bypass 
if ((Get-Module Microsoft.Online.SharePoint.PowerShell).Count -eq 0) {
        Import-Module Microsoft.Online.SharePoint.PowerShell -DisableNameChecking
    }

  
$TestInputs=$args
$domain=$TestInputs[0]
$userName=$TestInputs[1]
$password=Eg-O365Dcr -EncStr $TestInputs[2]
$proxycrdls=($TestInputs[3]).ToString().Split("#")
$proxyUsr=$proxycrdls[0]
$proxyPass=Eg-O365Dcr -EncStr $proxycrdls[1]
$proxyserverip=$TestInputs[4]
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() }

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

Try{
    $url = 'https://'+$domain+'-admin.sharepoint.com'
    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
        }
     }

    $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $userName, $(convertto-securestring $password -asplaintext -force)    
    Connect-SPOService -Url $url -Credential $cred 

    $spoSites=Get-SPOSite -Limit ALL | select Url,Status,Template,Title,Owner,WebsCount,StorageQuota,StorageUsageCurrent,ResourceUsageCurrent,ResourceUsageAverage,ResourceQuota,ResourceQuotaWarningLevel,LockState,LockIssue,LastContentModifiedDate 

    $extUsersMap = @{}

    foreach($site in $spoSites){
        # Here  we exclude the groups site collections
        if($site.Template -ne 'GROUP#0'){
            $spoURL=$site.Url
            $HashSet = New-Object 'System.Collections.Generic.HashSet[string]'  
            $y=0
            $stop="false"
            $i=0
            $extUsersCount=0
            try{
                $tempdate=($site.LastContentModifiedDate).toString().trim()
                $LastContentModifiedDate= [DateTime]::ParseExact($tempdate,$DateTimeFormat,[System.Globalization.DateTimeFormatInfo]::InvariantInfo,[System.Globalization.DateTimeStyles]::None)
                $LastContentModifiedDate1=(([datetime]$LastContentModifiedDate).ToString('MM/dd/yyyy HH:mm:ss tt')).toString()       
            }catch{
                $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
                Write-Error "Error Occured in SPOGetSites in date type casting -- $exceptionmsg "
                $LastContentModifiedDate1=$site.LastContentModifiedDate
            }
            Write-Host 'SpoSiteME~'$spoURL '~'$site.Status'~'$site.Template'~'$site.Title'~'$site.Owner'~'$site.WebsCount'~'$site.StorageQuota'~'$site.StorageUsageCurrent'~'$site.ResourceUsageCurrent'~'$site.ResourceUsageAverage'~'$site.ResourceQuota'~'$site.ResourceQuotaWarningLevel'~'$site.LockState'~'$site.LockIssue'~'$LastContentModifiedDate1
    
            Try{
                $testSite=Test-SPOSite $spoURL | select SiteUrl,PassedCount,FailedWarningCount,FailedErrorCount,Results
            }
            Catch [Microsoft.SharePoint.Client.ServerException]{
                $testSite=$null 
                #Write-Host 'Exception Occured in spogetsites' $_.Exception.Message
            }

            if($testSite -ne $null){
                foreach($tsite in $testSite){
                    $siteUrl=$tsite.SiteUrl
                    write-host 'SpoHealthME~'$siteUrl '~'$tsite.PassedCount'~'$tsite.FailedWarningCount'~'$tsite.FailedErrorCount
                    $results=$tsite.Results
                    foreach($res in $results){

                        write-host 'SpoHealthDD~'$siteUrl '~' $res.ToString().trim()                 
                    }
                }
            }
            do{ 
                Try{
                    $extUsers= Get-SPOExternalUser -SiteUrl $spoURL -Position $i -PageSize 50| select Email,DisplayName,UniqueId,AcceptedAs,WhenCreated,InvitedBy
                    $extUsersCount = $extUsers.count
                }
                Catch{
                    $ErrorMessage = $_.Exception.Message
                    #$FailedItem = $_.Exception.ItemName
                    Break
                }
                            
                if($extUsersCount=0){ 
                    $stop="true" 
                } 
                else{
                    foreach($user in $extUsers){
                        <#
                            If Administrator invites you then you will see the Aministrator Email Address in Invitedby 
                            If User requests the Administrator to Add them to the respective site then you will see UserEmailID#ext#@AdministratorEmailID in Invitedby 
                        #>
                        $InvitedBy=$user.InvitedBy

                        if($InvitedBy -ne $null){
                            $value=$user.Email+'~'+$user.DisplayName+'~'+$user.UniqueId+'~'+$user.AcceptedAs+'~'+$user.WhenCreated+'~'+$InvitedBy
                        }
                        else{
                            $value=$user.Email+'~'+$user.DisplayName+'~'+$user.UniqueId+'~'+$user.AcceptedAs+'~'+$user.WhenCreated+'~'+'-'
                        }                                                
                        $NoPrinting=$HashSet.Add($value)
                    }
                }
                $y=0;
            }While ($stop -eq "true") 

    
            if ($HashSet.count -gt 0){
                $extUsersMap.Add($spoURL, $HashSet) 
            }
        }
    }

    foreach ($usrMap in $extUsersMap.GetEnumerator()){

        $keys=($usrMap.Name).ToString()
        $values=$usrMap.Value
        Write-Host 'ExtCount~'$keys'~' $values.Count
                
        foreach ($DDline in $values.GetEnumerator()){

            Write-Host 'ExtDD~'$keys'~'$DDline
        }
    }
}
Catch{
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
     Write-Error "Error Occured in SPOGetSites -- $exceptionmsg "
}
