clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$egEncryPath=$egurkhaPath+"\lib\EGFileEncryption.psm1"
$egDatnKy=$egurkhaPath+'\lib\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]
$testfrqPrxyServer=($TestInputs[4]).ToString().Split("#")
$testfrquency=($testfrqPrxyServer[0].Trim())
$proxyserverip=($testfrqPrxyServer[1]).ToString().trim()

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



$Global:teamchannels=@{}
$Global:TeamsList = @()
$teamscount=0
$privateteams=0
$publicteams=0
$Global:totalchanlsCnt=0
$activeteams=0
$Inactiveteams=0

$rptPath=$egurkhaPath+'\agent\MTM\'+$reportingname
if(!(Test-Path -Path $rptPath )){
   $null =  New-Item -ItemType directory -Path $rptPath -WarningAction SilentlyContinue
}

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 "
    $_.Exception.Message
}


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

    Process
    {
        $query = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $Url
        $query=$query.Replace('ï»¿','')
        $query=$query.Replace(' ','')
        $resultarray = ConvertFrom-Csv -InputObject $query
        $reprts=$resultarray | ConvertTo-Json 
        $jsonreprt=@()
        $jsonreprt='{ "Usage" :['+$reprts+']}'
        $reports=$jsonreprt | ConvertFrom-Json
        $e=0
        for($i=0;$i -lt $reports.Usage.Length ;$i++ ){  
            $e++ 
            $reports.Usage[$i] |Export-Csv $filePath -Append -NoTypeInformation -Force
        }
    }
}

Function findingTeamsfromGroups(){
	[CmdletBinding()]
    Param(
        [Parameter(Mandatory=$true, Position=1)]
        [Object]$value, 
        [Parameter(Mandatory=$true, Position=3)]
        [Object]$header               
    )

    Process
    { 
        $id= $value.id
        $team = Invoke-RestMethod -Headers $header -Uri  https://graph.microsoft.com/v1.0/teams/$id/channels -Method Get
        #"Channel count for " + $value.displayName + " is " + $team.value.id.count

        If($team.value.id.count -ge 1)
        {
	        $Owner = Invoke-RestMethod -Headers $header -Uri  https://graph.microsoft.com/v1.0/Groups/$id/owners -Method Get
	        $memebers = Invoke-RestMethod -Headers $header -Uri  https://graph.microsoft.com/v1.0/Groups/$id/members -Method Get
	        $Teams = "" | Select "TeamsName","TeamType","createdDate","Channelcount","ChannelName","Owners","members","memebercount"
	        $Teams.TeamsName = $value.displayname
	        $Teams.TeamType = $value.visibility
	        $Teams.createdDate = $value.createdDateTime
	        $Teams.ChannelCount = $team.value.id.count
	        $Teams.ChannelName = $team.value.displayName -join ";"
	        $Teams.Owners = $Owner.value.userPrincipalName -join ";"
	        $Teams.members = $memebers.value.userPrincipalName -join ";"
            $Teams.memebercount = $memebers.value.userPrincipalName.count
	        $Global:TeamsList+= $Teams
            $Global:totalchanlsCnt+=$team.value.id.count
            $Global:teamchannels.add($Teams,$team.value.id.count)
            $Teams=$null
        }


    }
}



$flag=$false
foreach($inp in $GetInput){
    if($inp.StartsWith('[') -and $inp.Contains($domain)){
        $flag=$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
        }
    }
}

$path=(([XML]((Get-Package -Name AzureAD  | select SwidTagText)).SwidTagText).SoftwareIdentity.Meta.InstalledLocation)+'\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'
Add-Type -Path $path

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

try{
    $teamsoutput = Invoke-RestMethod -Method 'Get' -Headers $header -Uri "https://graph.microsoft.com/beta/groups?`$filter=resourceProvisioningOptions/any(c:c+eq+`'Team`')"
    #$teamsoutput.value.count   #| export-csv 'D:\todelete\allteams.csv'
    foreach($value in $teamsoutput.value)
    {

        try{

            findingTeamsfromGroups -value $value -header $header 
        }catch{
        ($_.Exception.Message) 
        ($_.ScriptStackTrace) 
            Start-Sleep -Seconds 1
            findingTeamsfromGroups -value $value -header $header 
         }
    }

}catch{
    
    Write-Error  "exception while running the Invoke-RestMethod for getting the teams "+($_.Exception.Message)+($_.ScriptStackTrace) 
}

$topchnls=$teamchannels.getenumerator() | Sort-Object -Property Value -Descending | select -first 10
foreach( $in in $topchnls)
{
$team=$in.key
write-host 'top10chanlteams#'$team.TeamsName ~!~ $team.createdDate ~!~ $team.memebercount ~!~ $team.Owners ~!~ $team.ChannelCount
}
foreach($team in $TeamsList)
{
    $teamscount++
    if($team.TeamType -eq 'Private')
    {
        $privateteams++
    }
   # Write-Host $team.TeamsName ~!~ $team.TeamType ~!~ $team.createdDate ~!~  $team.ChannelCount ~!~  $team.ChannelName ~!~ $team.Owners ~!~ ($team.members).toString().split(';').count
}


$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$ActUsrDtlcsv = $rptPath+'\ActiveUserDetail'+$timenow+'.csv'

$O365ActUsrDetlsurl= "https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail(period='D7')"
Eg-InvokeUrl -Url $O365ActUsrDetlsurl -filePath $ActUsrDtlcsv -header $header


$datelimit=(get-date).AddDays(-7)
try{
    $ActUsrDtlList= import-csv $ActUsrDtlcsv | Select-Object * | Where-Object { $_.HasTeamsLicense -eq 'TRUE' } | Sort-Object { $_.TeamsLastActivityDate -as [datetime] } -Descending 
}catch{
    $_.Exception
    Write-Error -Message "File not found. The $reportingname location does not contain Active User Details report"+($_.Exception.Message)+($_.ScriptStackTrace) 
}


   foreach($dev in $ActUsrDtlList){
            if($dev.TeamsLastActivityDate){
                $tmslstAct=[datetime]($dev.TeamsLastActivityDate)
                if($tmslstAct -le $datelimit)
                {
                    $Inactiveteams++
                    write-host 'inactive users#' $dev.UserPrincipalName ~!~ $dev.DisplayName ~!~ $dev.TeamsLastActivityDate
                }
            }
            else
            {
                $Inactiveteams++
                write-host 'inactive users#' $dev.UserPrincipalName ~!~ $dev.DisplayName ~!~ $dev.TeamsLastActivityDate
            }         
    }

if($ActUsrDtlList){ $activeteams=$ActUsrDtlList.count -$Inactiveteams }
Write-host 'measurescount#' $teamscount ~ $privateteams ~ ($teamscount-$privateteams) ~ $totalchanlsCnt ~ $activeteams ~ $Inactiveteams

$csvDir=$rptPath+'/'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'ActiveUserDetail'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'ServicesUserCounts'