[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


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

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

$lastruntime=((Get-date).AddMinutes($testFrequency)).ToUniversalTime() 

$proxyserver='http://'+$proxyserverip
$domain=Eg-GetDomain -userName $userName -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -IsIntial $true -proxyserver $proxyserver


if($domain){
    clear
    [System.Collections.ArrayList]$incidentIDs=@()
    try{
        $msGraphPath=$egurkhaPath+"\agent\O365\MsGraph"
        $keyFileNam = '\GraphDetailsKey.dat'
        $unProtPath= $msGraphPath+'\GraphDetails.dat'
        $kvalue= Get-Content -Path $msGraphPath$keyFileNam
        $null=Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.txt'
        $SkypeInput=$msGraphPath+"\GraphDetails.txt"
        $GetInput = Get-Content -Path $SkypeInput
    }catch{
        Write-Error -Message "File not found. The $GetInput location does not contain GraphDetails"
    }

    Function Eg-InvokeUrl(){
	    [CmdletBinding()]
        Param(
            [Parameter(Mandatory=$true, Position=1)]
            [String]$Url, 
            [Parameter(Mandatory=$true, Position=3)]
            [Object]$header               
        )

        Process
        {
           $query= Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
           $query=$query.value
           return $query
        }
    }
    $ClientSecretDetails=$false
    $flag=$false
    foreach($inp in $GetInput){
        if($inp.StartsWith('[') -and $inp.Contains($domain)){
            $flag=$true
            $ClientSecretDetails=$true
        }
        if($flag){
            if($inp.Contains("client_id")){
                $appId =$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("client_secret")){
                $appSecret =$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("TenantName")){
                $tenantID=$inp.ToString().Substring($inp.IndexOf('~')+1)
            }
            if($inp.Contains("Authority")){
                $authString = $inp.ToString().Substring($inp.IndexOf('~')+1)
                $authString=$authString+$domain
            }
            if($inp.Contains("Resource")){
                $Resource =$inp.ToString().Substring($inp.IndexOf('~')+1)
                $flag=$false            
            }
        }
    }

    if($ClientSecretDetails)
    {
        clear
        $path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
        Add-Type -Path $path
        $Resource="https://manage.office.com"
        $creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $appId, $appSecret
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
        $context = $authContext.AcquireTokenAsync($Resource, $creds).Result
        $authCode=$context.CreateAuthorizationHeader()
        $header = @{
            'Authorization'=$authCode
        }

        $ServicesCurrentStatus= "https://manage.office.com/api/v1.0/$domain/ServiceComms/CurrentStatus"
        $serviceCurrentStatus= Eg-InvokeUrl -Url $ServicesCurrentStatus  -header $header
        foreach ($srv in $serviceCurrentStatus)
        {  
            $Status=$srv.Status
            if(($Status -eq "Investigating") -or ($Status -eq "ServiceInterruption") -or ($Status -eq "Restoring") -or ($Status -eq "ServiceDegradation") -or ($Status -eq "ExtendedRecovery"))
            {
                if($srv.WorkloadDisplayName -eq 'Exchange Online')
                {
                    $DegradationIDs=$srv.IncidentIds.trim()
                    foreach($Did in $DegradationIDs){
                        $null=$incidentIDs.Add($Did)
                    }
                }
            }  
        }

        $O365Servicesurl= "https://manage.office.com/api/v1.0/$domain/ServiceComms/Messages"
        $serv= Eg-InvokeUrl -Url $O365Servicesurl  -header $header
        foreach($incidents in $serv)
        {

            $ID=$incidents.Id.trim()
            if($incidentIDs.Contains($ID))
            {
                $Status = $incidents.Status
                $ID = $incidents.Id
                $title = $incidents.Title
                $Affected = $incidents.AffectedTenantCount
                $ServiceName=$incidents.WorkloadDisplayName
                $Startime=$incidents.StartTime
                $Endtime =$incidents.EndTime
                $lastupdated=$incidents.LastUpdatedTime
                $messages=$incidents.Messages.messagetext
                $FeatureName= $incidents.Feature
                $type=$incidents.MessageType
                if((($lastupdated -gt $lastruntime) -or ($Endtime -eq $null) -or ($Endtime -gt $lastruntime)) -and ($type -eq "Incident")){
                        Write-Host $type  ~!~ "NOTOKSERVICE" ~!~  $Status ~!~  $ID ~!~  $title ~!~  $Affected   ~!~  $ServiceName ~!~  $Startime ~!~  $Endtime ~!~  $lastupdated ~!~  $FeatureName ~!~ $messages "##msage##"
                }
                elseif($type -eq "Maintenance"){
                    Write-Host $type ~!~ "MAINTAINANCE" ~!~ $Status ~!~  $ID ~!~  $title ~!~  $Affected   ~!~  $ServiceName ~!~  $Startime ~!~  $Endtime ~!~  $lastupdated ~!~  $FeatureName ~!~  $messages "##msage##"
                }
            }
        }
    }
    else
    {

    Try{
        clear
	    Connect-MsolService  -Credential $cred -AzureEnvironment $azureEnvArr[0]
	    $types = "Incident","Maintenance"
	    $MySession = New-SCSession -Credential $cred 
    }Catch{
        Write-error "Error Occured in O365ServHeal -- "$_.Exception.Message
    }

    foreach($type in $types)
    {
        $serv = Get-SCEvent -EventTypes $type  -SCSession $MySession  | sort ID, LastUpdatedTime
        $prvSrvcName = "" 
        $prvStartime = "" 
        $prvEndtime = "" 
        $prvlastupdated = "" 


            foreach($incidents in $serv)
            {
                if($incidents.AffectedServiceHealthStatus.ServiceName -eq 'Exchange Online')
                {
                $Status = $incidents.Status
                $ID = $incidents.Id
                $title = $incidents.Title
                $Affected = $incidents.AffectedTenantCount
                $ServiceName=$incidents.AffectedServiceHealthStatus.ServiceName
                $Startime=$incidents.StartTime
                $Endtime =$incidents.EndTime
        
                $lastupdated=$incidents.LastUpdatedTime
                $messages=$incidents.messages.messagetext
                $ServiceFeatureStatus=$incidents.AffectedServiceHealthStatus.ServiceFeatureStatus
                $FeatureName= $ServiceFeatureStatus.FeatureName
                $ServiceHealthCollection = New-Object System.Collections.ArrayList
                $finalSrvcHealth = $ServiceFeatureStatus
                if ((($lastupdated -gt $lastruntime) -or ($Endtime -eq $null)) -and ($type -eq "Incident") -and (($Status -eq "Investigating") -or ($Status -eq "Service interruption") -or ($Status -eq 
                "Restoring") -or ($Status -eq "Service degradation") -or ($Status -eq "Extended recovery"))) 
                {
                    Write-Host $type  ~!~ "NOTOKSERVICE" ~!~  $Status ~!~  $ID ~!~  $title ~!~  $Affected   ~!~  $ServiceName ~!~  $Startime ~!~  $Endtime ~!~  $lastupdated ~!~  $FeatureName ~!~ $messages 
                    "##msage##"
                }

               elseif(($type -eq "Incident") -and ($Endtime -gt $lastruntime) ){
                    Write-Host $type ~!~ "INCIDENTDETAILS"~!~  $Status ~!~  $ID ~!~  $title ~!~  $Affected   ~!~  $ServiceName ~!~  $Startime ~!~  $Endtime ~!~  $lastupdated ~!~  $FeatureName ~!~  $messages 
                    "##msage##"      
	           }
               elseif($type -eq "Maintenance"){
                    Write-Host $type ~!~ "MAINTAINANCE" ~!~ $Status ~!~  $ID ~!~  $title ~!~  $Affected   ~!~  $ServiceName ~!~  $Startime ~!~  $Endtime ~!~  $lastupdated ~!~  $FeatureName ~!~  $messages 
                    "##msage##"
                }
            }
        }
    }
    $MySession = $null
    }

}
