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

clear
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egurkhaPath=($scriptPath.Substring(0,$scriptPath.ToLower().IndexOf('egurkha')+7)).Trim()
$egEncryPath=$egurkhaPath+"\lib\EGFileEncryption.psm1"
$egDatnKy=$egurkhaPath+'\lib\GetDatnKeyFiles.psm1'
Import-Module $egEncryPath,$egDatnKy
#<#
$TestInputs=$args
$proxyUsr=$TestInputs[0]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[1]
$testfrqPrxyServer=($TestInputs[2]).ToString().Split("#")
$testfrquency=($testfrqPrxyServer[0].Trim())
$proxyserverip=($testfrqPrxyServer[1]).ToString().trim()
$graphDtls=$TestInputs[3]
#>

$graphDtlsArr=$graphDtls.ToString() -split '~!~'
$appId=$graphDtlsArr[0]
$appSecret=$graphDtlsArr[1]
$authString=$graphDtlsArr[2]
$resource=$graphDtlsArr[3]

$langPath=$egurkhaPath+'\agent\config\O365_lang.ini'
$encTyp=Eg-GetINIContent -Path $langPath -Subject 'File_Type' -Key 'encoding'

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.ToString().ToLower().Contains('none')){
    $proxyserver='http://'+$proxyserverip
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUsr.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -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
    }
}

##### LOG-Start ###########
$logDir=$egurkhaPath+'\agent\MTM\'+$rptNam+'\logs'
if(!(Test-Path -Path $logDir)){
    $null=New-Item -ItemType directory -Path $logDir
}
$LogFile = $logDir+"\MTMteamsInv.log"
$LogFile1 = $logDir+"\MTMteamsInv1.log"
$tmsInvDebug=$false

Function Write-Log {
	Param ([string]$string)
	if($tmsInvDebug){
		[string]$date = Get-Date -Format G
		( "[" + $date + "] -  [O365]  -  " + $string ) | Out-File -FilePath $LogFile -Append
		if ([System.IO.File]::Exists($LogFile) -and (Get-Item $LogFile).length -gt 2mb) {  #if the size of file is greater than 1MB 
			if([System.IO.File]::Exists($LogFile1)){  #if logfile1 already exists, delete logfile1 
				Remove-Item $LogFile1 
			} 
			Rename-Item $LogFile $LogFile1   
		}
	}
}
##### LOG - End ##########

$Global:TeamsList = @()
$teamscount=0
$privateteams=0
$publicteams=0
$activeteams=0
$Inactiveteams=0

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

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 = [System.Text.Encoding]::$encTyp.GetString((Invoke-WebRequest -Method Get -Headers $header -Uri $Url -UseBasicParsing).RawContentStream.ToArray())
        #$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 -Encoding $encTyp -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
        }
    }
}

$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{
    #$grpURI="https://graph.microsoft.com/beta/groups?`$filter=resourceProvisioningOptions/any(c:c+eq+`'Team`')"
    $grpURI="https://graph.microsoft.com/v1.0/groups?$select=id,resourceProvisioningOptions"
    $tmsCnt=0;$recCnt=0
    while($true){
        $teamsoutput = Invoke-RestMethod -Method 'Get' -Headers $header -Uri $grpURI #"https://graph.microsoft.com/beta/groups?`$filter=resourceProvisioningOptions/any(c:c+eq+`'Team`')"
        #$teamsoutput.value.count   #| export-csv -Encoding $encTyp 'D:\todelete\allteams.csv'
        foreach($value in $teamsoutput.value)
        {
            $recCnt++
            if($value.resourceProvisioningOptions -eq 'Team'){
                $tmsCnt++
                $Teams = "" | Select "TeamsName","TeamType","createdDate"
	            $Teams.TeamsName = $value.displayname
	            $Teams.TeamType = $value.visibility
	            $Teams.createdDate = $value.createdDateTime
	            $Global:TeamsList+= $Teams
                $Teams=$null    
            }
        }
        if($teamsoutput.'@odata.nextLink' -eq $null){break;}
        $grpURI=$teamsoutput.'@odata.nextLink'
    }

}catch{
    Write-Log("catch - Record count -->> $recCnt")
    Write-Log("catch - Teams count -->> $tmsCnt")
    #Write-Error "exception while running the Invoke-RestMethod for getting the teams ($_.Exception.Message) ($_.ScriptStackTrace)" 
    $ExcepMsg='['+(Split-Path ($_.InvocationInfo.ScriptName) -leaf)+'] Exception Occured in "getting Records" -- [Line Number] '+$_.InvocationInfo.ScriptLineNumber+' -- '+$_.Exception
    Write-Error $ExcepMsg
}
Write-Log("Record count -->> "+$recCnt)
Write-Log("Teams count -->> "+$tmsCnt)
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'
Eg-RemoveGraphcsvFiles -rmvPath $ActUsrDtlcsv

$O365ActUsrDetlsurl= "https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail(period='D7')"
Eg-InvokeUrl -Url $O365ActUsrDetlsurl -filePath $ActUsrDtlcsv -header $header
[System.GC]::GetTotalMemory($true) | out-null

$datelimit=(get-date).AddDays(-7)
try{
    $ActUsrDtlList= import-csv $ActUsrDtlcsv -Encoding $encTyp | 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)
    $ExcepMsg='['+(Split-Path ($_.InvocationInfo.ScriptName) -leaf)+'] "File not found. The $reportingname location does not contain Active User Details report" -- [Line Number] '+$_.InvocationInfo.ScriptLineNumber+' -- '+$_.Exception
    Write-Error -Message $ExcepMsg
    Write-Log("catch -- ActiveUserDetail --->> $ExcepMsg")
}


   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 }
if($teamscount -gt 0){
    $resStr='measurescount#'+$teamscount+'~'+$privateteams+'~'+($teamscount-$privateteams)+'~-5~'+$activeteams+'~'+$Inactiveteams
    Write-host $resStr
}else{
    $resStr='measurescount#-5~-5~-5~-5~'+$activeteams+'~'+$Inactiveteams
    Write-host $resStr
}

$csvDir=$rptPath+'/'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'ActiveUserDetail'
Eg-DeleteCsvFiles -FilePath $csvDir -Pattern 'ServicesUserCounts'
[System.GC]::GetTotalMemory($true) | out-null