<#
    /*****************************************************************************
    Author            :       Mounika Kuna
    Purpose           :       Provides Office 365 License Details by User
    Created           :       18/07/2020    
    /*****************************************************************************
#>

$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=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy -WarningAction SilentlyContinue

#<#
$TestInputs=$args
$username=$TestInputs[0]
$password=Eg-O365Dcr -EncStr $TestInputs[1]
$proxyUser=$TestInputs[2]
$proxyPass=Eg-O365Dcr -EncStr $TestInputs[3]
$proxyserver=$TestInputs[4]
$readingdate=[datetime]$TestInputs[5]
$rptNam=$TestInputs[6]
$graphDetails=$TestInputs[7]
if($graphDetails -and $graphDetails -ne 'none'){
    $graphDetailsArr=($graphDetails).ToString() -Split ("~!~")
    $appId=$graphDetailsArr[0]
    $appSecret=$graphDetailsArr[1]
    $authString=$graphDetailsArr[2]
    $resource=$graphDetailsArr[3]
}
#>

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

if($proxyUser.toString().toLower().Trim() -eq 'none') { $proxyUser=$proxyUser.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserver.toString().toLower().Trim().Contains('none')) { $proxyserver=$proxyserver.toString().toLower().Trim() }
if(!$proxyserver.ToString().ToLower().Contains('none')){
    [system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyserver)
    if($proxyUser.ToString().ToLower() -ne 'none' -and $proxyPass.ToString().ToLower() -ne 'none'){
        $proxyCred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $proxyUser, $(convertto-securestring $proxyPass -asplaintext -force)
        [system.net.webrequest]::defaultwebproxy.credentials =$proxyCred
        [system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
    }
}

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

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

$timenow = [int][double]::Parse((Get-Date -UFormat %s))
$O365ActiveUserDetCSV=$rptPath+'\O365ActiveUserDet'+$timenow+'.csv'
Eg-RemoveGraphcsvFiles -rmvPath $O365ActiveUserDetCSV

$url = "https://graph.microsoft.com/v1.0/reports/getOffice365ActiveUserDetail(period='D7')"
while($true){
    Eg-InvokeGraphUrl -Url $url -filePath $O365ActiveUserDetCSV -appId $appId -appSecret $appSecret -authString $authString -resource $resource
    $TotalO365ActiveUserDet=Import-Csv $O365ActiveUserDetCSV -Encoding $encTyp
    $url=$TotalO365ActiveUserDet.'@odata.nextLink'
    if($url -eq $null -or $url -eq ''){
        break
    }
}
[System.GC]::GetTotalMemory($true) | out-null
$diffence=(NEW-TIMESPAN –Start $readingdate –End (Get-Date) | Select-Object Days).Days
$notFirsttime = $false
while($diffence -ge 1)
{
    if($notFirsttime){ $readingdate=$readingdate.AddDays(1) }
    $actualdate=$readingdate
    $notFirsttime = $true
    $TotalO365ActiveUser =$TotalO365ActiveUserDet | Where-Object { [datetime]$_.ReportRefreshDate -eq $actualdate }       
    if($TotalO365ActiveUser)
    {
        Write-Host 'ReadDate for the Date#'$actualdate.tostring(“yyyy-MM-dd”)
        break
    }
    else
    {
        Write-Host 'thereIs No Data on#'$actualdate.tostring(“yyyy-MM-dd”)
    }
    $diffence=$diffence-1
}
[System.GC]::GetTotalMemory($true) | out-null
try{
	$TotalO365ActiveUser = $TotalO365ActiveUser | Where-Object { $_.UserPrincipalName -ne '(Unknown)' }
    foreach($User in $TotalO365ActiveUser){
        $HasExchangeLicense=0
        if($User.HasExchangeLicense -eq 'True'){
           $HasExchangeLicense=1
        }
        $HasOneDriveLicense=0
        if($User.HasOneDriveLicense -eq 'True'){
           $HasOneDriveLicense=1
        }
        $HasSharePointLicense=0
        if($User.HasSharePointLicense -eq 'True'){
           $HasSharePointLicense=1
        }
        $HasSkypeForBusinessLicense=0
        if($User.HasSkypeForBusinessLicense -eq 'True'){
           $HasSkypeForBusinessLicense=1
        }
        $HasYammerLicense=0
        if($User.HasYammerLicense -eq 'True'){
           $HasYammerLicense=1
        }
        $HasTeamsLicense=0
        if($User.HasTeamsLicense -eq 'True'){
           $HasTeamsLicense=1
        }

        $UserId = $User.UserPrincipalName
        $TotalLicenses=$HasExchangeLicense+$HasOneDriveLicense+$HasSharePointLicense+$HasSkypeForBusinessLicense+$HasYammerLicense+$HasTeamsLicense
        if($TotalLicenses -ne '0'){
            $TotalLicenseDD = $UserId+'##'+$User.ExchangeLicenseAssignDate+'~!~'+$User.OneDriveLicenseAssignDate+'~!~'+$User.SharePointLicenseAssignDate+'~!~'+$User.SkypeForBusinessLicenseAssignDate+'~!~'+$User.YammerLicenseAssignDate+'~!~'+$User.TeamsLicenseAssignDate+'~!~'+$User.AssignedProducts+'~!~'+$User.ExchangeLastActivityDate+'~!~'+$User.OneDriveLastActivityDate+'~!~'+$User.SharePointLastActivityDate+'~!~'+$User.SkypeForBusinessLastActivityDate+'~!~'+$User.YammerLastActivityDate+'~!~'+$User.TeamsLastActivityDate
            Write-Host 'TotalLicenseDD='$TotalLicenseDD
        }

        Write-Host 'info&Measures='$UserId'~'$TotalLicenses'~'$HasExchangeLicense'~'$HasOneDriveLicense'~'$HasSharePointLicense'~'$HasSkypeForBusinessLicense'~'$HasYammerLicense'~'$HasTeamsLicense		
    }
}catch{    
    $exceptionmsg=($_.Exception.Message)+($_.ScriptStackTrace) 
	Write-error "Error Occured in O365LicDtlsByUsrTest Script >>> "$exceptionmsg 
}
[System.GC]::GetTotalMemory($true) | out-null
if([System.IO.File]::Exists($O365ActiveUserDetCSV) -eq 'True'){
    Remove-Item $O365ActiveUserDetCSV
}
