$OutputEncoding = [console]::InputEncoding = [console]::OutputEncoding = New-Object System.Text.UTF8Encoding
$PSDefaultParameterValues = @{'*:Encoding' = 'utf8'}

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egurkhaPath=($scriptPath.Substring(0,$scriptPath.ToLower().IndexOf('egurkha')+7)).Trim()
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy

clear
#<#
$TestInputs=$args
$username=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxycrdls=($TestInputs[2]).ToString().Split("#")
$proxyUsr=$proxycrdls[0]
$proxyPass=Eg-O365Dcr -EncStr $proxycrdls[1]
$proxyserverip=$TestInputs[3]
$tenantName=$TestInputs[4]
$tenantAPIKey=$TestInputs[5]

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() }
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
    }
}

function Skip-CertificateCheck {
if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
{
$certCallback = @"
    using System;
    using System.Net;
    using System.Net.Security;
    using System.Security.Cryptography.X509Certificates;
    public class ServerCertificateValidationCallback
    {
        public static void Ignore()
        {
            if(ServicePointManager.ServerCertificateValidationCallback ==null)
            {
                ServicePointManager.ServerCertificateValidationCallback += 
                    delegate
                    (
                        Object obj, 
                        X509Certificate certificate, 
                        X509Chain chain, 
                        SslPolicyErrors errors
                    )
                    {
                        return true;
                    };
            }
        }
    }
"@
    Add-Type $certCallback
 }
[ServerCertificateValidationCallback]::Ignore()

}

function Eg-InvokeUrl {
    [CmdletBinding()]
    Param (
        [Parameter(Mandatory=$true)]
        [String]$Uri, 
        [Parameter(Mandatory=$true)]
        [HashTable]$Headers
    ) 
    Process {
        Skip-CertificateCheck
        $result = Invoke-RestMethod -Method Get -Uri $Uri -Headers $Headers
        return $result
    }
}

function Set-Credentials {
    [CmdletBinding()]
    Param (
       [Parameter(Mandatory=$true)]
       [string]$username,
       [Parameter(Mandatory=$true)]
       [string]$password
    )
    
    $pair = "${username}:${password}"
    $bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
    $base64 = [System.Convert]::ToBase64String($bytes)
 
    $basicAuthValue = "Basic $base64"
    return $basicAuthValue
}

function Set-Headers {
    [CmdletBinding()]
    Param (
       [Parameter(Mandatory=$true)]
       [string]$Authorization,
       [Parameter(Mandatory=$true)]
       [string]$Version
    )
    $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
    $headers.Add("Authorization", $Authorization) 
    $headers.Add("aw-tenant-code", $APIKey)
    $headers.Add("Content-Type", "application/json")

    if($Version -and $Version -eq 2){
        $headers.Add("Accept", "application/json;version=2")
    }else{
        $headers.Add("Accept", "application/json")
    }
    return $headers
}

try {
    $credentials = Set-Credentials -username $username -password $password
    $headers = Set-Headers -Authorization $credentials -Version 2

    $tenantURL = $null
    if($tenantName -and $tenantName -ne 'none'){
        $tenantName = $tenantName.Trim()
        $tenantName = $tenantName.TrimEnd("/")
        if ($tenantName -ilike "https://*") {
            $tenantURL = $tenantName
        } elseif ($tenantName -ilike "http://*") {
            $tenantName = $tenantName -ireplace "http://"
            $tenantURL = "https://" + $tenantName
        } else {
            $tenantURL = "https://" + $tenantName
        }
    }

    if($tenantURL){
        $groupURL = $tenantURL + "/api/system/groups/search"
        $groupDetails = Eg-InvokeUrl -Uri $groupURL -Headers $headers
        if ($groupDetails) {
            foreach ($groupDetail in $groupDetails.OrganizationGroups) {
                $groupUuid = $groupDetail.Uuid
                $groupName = $groupDetail.Name
                if($groupUuid){
                    $certificateURL = $tenantURL + "/api/system/groups/" + $groupUuid + "/apns"
                    try {
                        $certificate = Eg-InvokeUrl -Uri $certificateURL -Headers $headers
                        if($certificate){
                            $AppleId = $certificate.apple_id
                            $CertificateType = $certificate.certificate_type
                            $ThumbPrint = $certificate.thumbprint
                            $IssuedBy = $certificate.issued_by
                            $IssuedTo = $certificate.issued_to
                            $ValidFrom = $certificate.valid_from
                            $ValidTo = $certificate.valid_to
                            $CurrentSetting = $certificate.current_setting
                            $ChildPermission = $certificate.child_permission
                            Write-Host 'DD~'$groupName'~'$AppleId'~'$CertificateType'~'$ThumbPrint'~'$IssuedBy'~'$IssuedTo'~'$ValidFrom'~'$ValidTo'~'$CurrentSetting'~'$ChildPermission  
                        }
                    } catch {
                        #$StatusCode = $_.Exception.Response.StatusCode.value__
                        Write-Error ('Exception Occured while getting certificate details for ' + $groupName + ' - ' + $_.Exception.Message)
                    }
                }
            }
        }
    }
} catch {
    #$StatusCode = $_.Exception.Response.StatusCode.value__
    $ErrorMessage=([string]$_.Exception)+($_.ScriptStackTrace)
    Write-Error ('Exception occurred while getting group details - '+$ErrorMessage)
}