#prerequisite: .net SDK - https://dotnet.microsoft.com/en-us/download
#pass env id as param
#https://github.com/svdoever/svdoever.github.io/blob/2afce8fa91dba2a08d1940c23910abd73ac97f7e/src/pages/XM_Cloud_build_and_deploy_like_a_pro.md?plain=1#L2
#https://thesitecorist.net/2022/12/19/sitecore-xm-cloud-logs/
#https://www.sergevandenoever.nl/XM_Cloud_build_and_deploy_like_a_pro/

[CmdletBinding()]
Param
(
	[string] $orgClientId="fdsfsfsd",
	[string] $orgClientSecret="fdsdfs-sfdds",
	[string] $envId="sfdsfsd",
	[string] $cmUrl="https://xmc-sdfsfs-dsfsdsdf-prod.sitecorecloud.io/",
	[string] $outputPath="."	
)
$watch = [System.Diagnostics.Stopwatch]::StartNew()
$watch.Start() # Timer start

$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Write-Host("Start Date/Time - $time")

function ConnecttoXMCEnvironment()
{
	dotnet new tool-manifest --force
	dotnet tool install Sitecore.CLI --add-source https://sitecore.myget.org/F/sc-packages/api/v3/index.json
	dotnet tool restore
	Dotnet sitecore init
	dotnet sitecore plugin add -n Sitecore.DevEx.Extensibility.Xmcloud
	#add more plugins here
	#dotnet sitecore cloud login #- this pops the login page that is intrusive
	dotnet sitecore cloud login --client-credentials true --client-id $orgClientId --client-secret $orgClientSecret --allow-write
    dotnet sitecore connect -r xmcloud --cm $cmUrl --allow-write true --environment-name default
}

function DownloadDeploymentLogs()
{
	
	$depPath=$outputPath + "\deploylogs"
	write-host "Downloading XMC deploy log list to "$depPath
	$depLogs=dotnet sitecore cloud deployment list --environment-id  $envId --json | ConvertFrom-Json #Get deploy log list
	
	foreach($depLog in $depLogs)
	{	
		#write-host $depObj.id		
		if($depLog.id) {dotnet sitecore cloud deployment log --deployment-id  $depLog.id --path $depPath}
	}	
}

function DownloadAllEnviromentLogs()
{	
	$envLogPath=$outputPath + "\envlogs"	
	write-host "Downloading XMC Env log list to "$envLogPath
	$envLogs=dotnet sitecore cloud environment log list -id $envId #Get env log list
	#write-host($envLogs)	
	foreach($envLog in $envLogs)
	{	
		if ($envLog.Trim() -Match "-") {
			
			$logFileName=$envLog.Trim().Split("-")[1].Trim()
			write-host "Downloading log file named: "$logFileName
						
			dotnet sitecore cloud environment log download --environment-id   $envId --log $logFileName  --path .\envlogs --timeout 600
		}
	}
}

function DownloadLatestEnviromentLogs()
{	
	$envLogPath=$outputPath + "\envlogs"	
	write-host "Downloading XMC latest Env log list to "$envLogPath
	$envLogs=dotnet sitecore cloud environment log list --latest --environment-id $envId #Get env log list
	write-host("Latest logs:" + $envLogs)	
	foreach($envLog in $envLogs)
	{	
		if ($envLog.Trim() -Match "-") {
			
			$logFileName=$envLog.Trim().Split("-")[1].Trim()
			write-host "Downloading log file named: "$logFileName
						
			dotnet sitecore cloud environment log download --environment-id   $envId --log $logFileName  --path $envLogPath --timeout 600
		}
	}
}

function CleanLogsFolder()
{
	Get-ChildItem -Path (Join-Path $PSScriptRoot ".\deploylogs") | ForEach-Object {
		$dataPath = $_.FullName
		write-host($dataPath)

		Get-ChildItem -Path $dataPath -Exclude ".gitkeep" -Recurse | Remove-Item -Force -Recurse -Verbose
	}

	Get-ChildItem -Path (Join-Path $PSScriptRoot ".\envlogs") | ForEach-Object {
		$deployPath = $_.FullName
		write-host($deployPath)
		
		Get-ChildItem -Path $deployPath -Exclude ".gitkeep" -Recurse | Remove-Item -Force -Recurse -Verbose
	}
}

#CleanLogsFolder #Optional call
ConnecttoXMCEnvironment
DownloadDeploymentLogs
DownloadAllEnviromentLogs #first time download
DownloadLatestEnviromentLogs #incremental download

$watch.Stop() # Stopping the timer
Write-Host "Execution time - " $watch.Elapsed # Print script execution time

Write-Host("Done")