[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egInstallpath=Get-ChildItem Env:EGURKHA_INSTALL_DIR |Select Value
$egurkhaPath=$egInstallpath.Value.ToString()
$scriptPath =split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy -WarningAction SilentlyContinue

clear
    ######***GUI  form ****#######
$form = New-Object System.Windows.Forms.Form
$flowlayoutpanel = New-Object System.Windows.Forms.FlowLayoutPanel
$buttonOK = New-Object System.Windows.Forms.Button

$O365DtlsLbl=New-Object System.Windows.Forms.Label
$O365UsrLbl=New-Object System.Windows.Forms.Label
$O365PassLbl=New-Object System.Windows.Forms.Label
$O365UsrTxtBx=New-Object System.Windows.Forms.TextBox
$O365PassTxtBx=New-Object System.Windows.Forms.TextBox 
    
$prxyDtlsLbl=New-Object System.Windows.Forms.Label
$prxyHostLbl=New-Object System.Windows.Forms.Label
$prxyPortLbl=New-Object System.Windows.Forms.Label
$prxyUsrLbl=New-Object System.Windows.Forms.Label
$prxyPassLbl=New-Object System.Windows.Forms.Label
$prxyHostTxtBx=New-Object System.Windows.Forms.TextBox
$prxyPortTxtBx=New-Object System.Windows.Forms.TextBox
$prxyUsrTxtBx=New-Object System.Windows.Forms.TextBox
$prxyPassTxtBx=New-Object System.Windows.Forms.TextBox    
      
$grphlDtlabel=New-Object System.Windows.Forms.Label
$grphAppLbl=New-Object System.Windows.Forms.Label
$grphAppTxtBx=New-Object System.Windows.Forms.TextBox    
$grphCIDLbl=New-Object System.Windows.Forms.Label
$grphCIDTxtBx=New-Object System.Windows.Forms.TextBox
$grphCSecrtLbl=New-Object System.Windows.Forms.Label
$grphCSecrtTxtBx=New-Object System.Windows.Forms.TextBox
  
$formsize = 375
$form.Controls.Add($O365DtlsLbl)
$form.Controls.Add($O365UsrLbl)
$form.Controls.Add($O365UsrTxtBx)
$form.Controls.Add($O365PassLbl)
$form.Controls.Add($O365PassTxtBx)

$form.Controls.Add($prxyDtlsLbl)
$form.Controls.Add($prxyHostLbl)
$form.Controls.Add($prxyHostTxtBx)
$form.Controls.Add($prxyPortLbl)
$form.Controls.Add($prxyPortTxtBx)
$form.Controls.Add($prxyUsrLbl)
$form.Controls.Add($prxyUsrTxtBx)
$form.Controls.Add($prxyPassLbl)
$form.Controls.Add($prxyPassTxtBx)

$form.Controls.Add($grphlDtlabel)
$form.Controls.Add($grphAppLbl)
$form.Controls.Add($grphAppTxtBx)
$form.Controls.Add($grphCIDLbl)
$form.Controls.Add($grphCIDTxtBx)
$form.Controls.Add($grphCSecrtLbl)
$form.Controls.Add($grphCSecrtTxtBx)

$form.Controls.Add($buttonOK)

$form.AcceptButton = $buttonOK
$form.AutoScaleDimensions = '8, 17'
$form.AutoScaleMode = 'Font'
$form.ClientSize = "428 , $formsize"
$form.FormBorderStyle = 'FixedDialog'
$form.Margin = '5, 5, 5, 5'
$form.MaximizeBox = $False
$form.MinimizeBox = $False
$form.Name = 'form1'
$form.StartPosition = 'CenterScreen'
$form.Text = 'Generate MS Graph Dat'
$form.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::Fixed3D

$O365DtlsLbl.Location="38,15"
$O365DtlsLbl.Anchor="Bottom, Left"
$O365DtlsLbl.Text="&Global Admin Credentails:"
$O365DtlsLbl.Size="200,20"
$O365UsrLbl.Location="58,38"
$O365UsrLbl.Anchor="Bottom, Left"
$O365UsrLbl.Text="&Username"
$O365UsrLbl.Size="115,20"
$O365UsrTxtBx.Location="175,38"
$O365UsrTxtBx.Name="O365User"
$O365UsrTxtBx.Size="200,20"
$O365UsrTxtBx.Text=""
$O365PassLbl.Location="58,67"
$O365PassLbl.Anchor="Bottom, Left"
$O365PassLbl.Text="&Password"
$O365PassLbl.Size="115,20"
$O365PassTxtBx.Location="175,67"
$O365PassTxtBx.Name="O365Pass"
$O365PassTxtBx.Size="200,20"
$O365PassTxtBx.Text=""
$O365PassTxtBx.PasswordChar='*'

$prxyDtlsLbl.Location="38,95"
$prxyDtlsLbl.Anchor="Bottom, Left"
$prxyDtlsLbl.Text="&Proxy Details :"
$prxyDtlsLbl.Size="100,20"
$prxyHostLbl.Location="58,118"
$prxyHostLbl.Anchor="Bottom, Left"
$prxyHostLbl.Text="&Host IP"
$prxyHostLbl.Size="115,20"
$prxyHostTxtBx.Location="175,118"
$prxyHostTxtBx.Name="ProxyHost"
$prxyHostTxtBx.Size="120,20"
$prxyHostTxtBx.Text="none"
$prxyPortLbl.Location="298,119"
$prxyPortLbl.Anchor="Bottom, Left"
$prxyPortLbl.Text="&Port"
$prxyPortLbl.Size="25,20"
$prxyPortTxtBx.Location="325,118"
$prxyPortTxtBx.Name="Port"
$prxyPortTxtBx.Size="50,20"
$prxyPortTxtBx.Text="none"
$prxyUsrLbl.Location="58,145"
$prxyUsrLbl.Anchor="Bottom, Left"
$prxyUsrLbl.Text="&Username"
$prxyUsrLbl.Size="115,20"
$prxyUsrTxtBx.Location="175,145"
$prxyUsrTxtBx.Name="ProxyUser"
$prxyUsrTxtBx.Size="200,20"
$prxyUsrTxtBx.Text="none"
$prxyPassLbl.Location="58,173"
$prxyPassLbl.Anchor="Bottom, Left"
$prxyPassLbl.Text="&Password"
$prxyPassLbl.Size="115,20"
$prxyPassTxtBx.Location="175,173"
$prxyPassTxtBx.Name="ProxyPass"
$prxyPassTxtBx.Size="200,20"
$prxyPassTxtBx.Text="none"
$prxyPassTxtBx.PasswordChar='*'

$grphlDtlabel.Location="38,200"  
$grphlDtlabel.Anchor="Bottom, Left"
$grphlDtlabel.Text="&O365 MS Graph Details:"
$grphlDtlabel.Size="200,20"
$grphAppLbl.Location="58,223"  
$grphAppLbl.Anchor="Bottom, Left"
$grphAppLbl.Text="&App Name"
$grphAppLbl.Size="115,20"
$grphAppTxtBx.Location="175,223"  
$grphAppTxtBx.Name="appName"
$grphAppTxtBx.Size="200,20"
$grphAppTxtBx.Text=""
$grphCIDLbl.Location="58,249" 
$grphCIDLbl.Anchor="Bottom, Left"
$grphCIDLbl.Text="&Client ID"
$grphCIDLbl.Size="115,20"
$grphCIDTxtBx.Location="175,249"
$grphCIDTxtBx.Name="clientId"
$grphCIDTxtBx.Size="200,20"
$grphCIDTxtBx.Text=""
$grphCSecrtLbl.Location="58,275" 
$grphCSecrtLbl.Anchor="Bottom, Left"
$grphCSecrtLbl.Text="&Client Secret"
$grphCSecrtLbl.Size="115,20"

$grphCSecrtTxtBx.Location="175,275"   
$grphCSecrtTxtBx.Name="clientSecret"
$grphCSecrtTxtBx.Size="200,20"
$grphCSecrtTxtBx.Text=""
    
$buttonOK.Anchor = 'Bottom, Right'
$buttonOK.DialogResult = 'OK'
$buttonOK.Location = "175, 310"
$buttonOK.Margin = '4, 4, 4, 4'
$buttonOK.Name = 'buttonOK'
$buttonOK.Size = '100, 30'
$buttonOK.TabIndex = 0
$buttonOK.Text = '&OK'
$frmDialog=$form.ShowDialog()

if($frmDialog -eq 'OK' ){
    $AdminuserName=$O365UsrTxtBx.Text
    $password=$O365PassTxtBx.Text
    $proxyHost=$prxyHostTxtBx.Text
    $proxyPort=$prxyPortTxtBx.Text
    $proxyUsr=$prxyUsrTxtBx.Text
    $proxyPass=$prxyPassTxtBx.Text  
    $applicationName=$grphAppTxtBx.Text
    $client_id=$grphCIDTxtBx.Text
    $client_secret=$grphCSecrtTxtBx.Text

    if($proxyHost -eq "" -or $proxyport -eq "" -or $proxyUsr -eq "" -or $AdminuserName -eq "" -or $password -eq "" -or $applicationName -eq '' -or $client_id -eq '' -or $client_secret -eq ''){
        Write-Host "Re-run the script with all the inputs...." -ForegroundColor Red
        Exit
    }

    $writDir=$egurkhaPath+'\agent\O365\MsGraph'
    if(!(Test-Path -Path $writDir)){
        $null=New-Item -ItemType directory -Path $writDir
    }
    $cred = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $AdminuserName, $(convertto-securestring $password -asplaintext -force)
    if($proxyHost -notcontains 'none' -and $proxyPort -notcontains 'none' ){
        $proxyserver='http://'+$proxyHost+':'+$proxyPort
        [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.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
        }
    }

    $azureVal=Eg-GetAzureEnv -UserName $AdminuserName
    $azureEnvArr=$azureVal.Split(',')
    Try{
        Connect-MsolService -Credential $cred -AzureEnvironment $azureEnvArr[0] -ErrorAction Stop
    }
    Catch {
        $ErrorMessage = $_.Exception.Message
        Write-Host $ErrorMessage -ForegroundColor Red
        Exit
    }
    $iDomain=Get-MsolDomain | where{$_.IsInitial -eq $true}|select Name
    $tenantName=$iDomain.Name
    $authority = "https://login.microsoftonline.com/"
    $resource = "https://graph.microsoft.com"

    if($applicationName -ne $null -and $applicationName -ne '' -and $client_id -ne $null -and $client_id -ne '' -and $client_secret -ne $null -and $client_secret -ne '' -and $tenantName -ne $null -and $tenantName -ne ''){
        $keyFileNam='\GraphDetailsKey.dat'
        $keyPath=$writDir+$keyFileNam
        $unProtFile=$writDir+'\GraphDetails.dat'
        if(Test-Path $unProtFile -PathType Leaf){
            $unProtPath=$writDir+'\GraphDetails.dat'
            $kvalue=Get-Content -Path $keyPath
            Unprotect-File $unProtPath -Algorithm AES -KeyAsPlainText $kvalue -DstSuffix '.txt'
        }

        $chkNam="-"+$tenantName+"]"
        $writPath=$writDir+'\GraphDetails.txt'
        if(Test-Path $writPath -PathType Leaf){
            $dtls=Get-Content -Path $writPath
            $j=0
            $wpath1=$writDir+'\GraphDetails1.txt'
            for($i=0;$i -lt $dtls.Length;$i++){
                if($dtls[$i] -match $chkNam){
                    $i=$i+8
                }
                Add-Content -Path $wpath1 -Value $dtls[$i]
            }
            Remove-Item $writPath
            if(Test-Path $wpath1 -PathType Leaf){
                Rename-Item $wpath1 'GraphDetails.txt'
            }
        }

        $null='['+$applicationName+'-'+$tenantName+']'| Add-Content $writPath -PassThru
        $null='client_id~'+$client_id| Add-Content $writPath -PassThru
        $null='client_secret~'+$client_secret| Add-Content $writPath -PassThru
        $null='TenantName~'+$tenantName| Add-Content $writPath -PassThru
        $null='Authority~'+$authority| Add-Content $writPath -PassThru
        $null='Resource~'+$resource| Add-Content $writPath -PassThru
        "`n"| Add-Content $writPath

        $key=Get-CryptoKey -FileDir $writDir -FileName $keyFileNam
        $null=Protect-File $writPath -Algorithm AES -KeyAsPlainText $key -RemoveSource

        Write-Host 'MsGraph dat file created successfully'
    }
    else{
        Write-Host 'MsGraph dat file not created'
    }
}
else{
    Write-Host 'Exiting...'
    exit
}