#!/bin/pwsh
. "$PSScriptRoot/Context.ps1";
. "$PSScriptRoot/BrowserAutomation.ps1";

function Install-AmdSoftwarePackage() {
    param(
        [Context] $context,
        [string] $url
    )

    $tempDir = $context.GetTempDirectory();
    $cookieBannerSelector = "#onetrust-consent-sdk";
    $osSelector = ".os-group:first-of-type";
    $summarySelector = "$osSelector summary:first-of-type";
    $downloadSelector = "$osSelector .driver:first-of-type a:first-of-type";

    $action = {
        param([OpenQA.Selenium.Firefox.FirefoxDriver] $browser)

        $summary = $browser.FindElement([OpenQA.Selenium.By]::CssSelector($summarySelector));

        if (-not ([bool]$summary.GetAttribute("aria-expanded"))) {
            $summary.Click();
        }

        $downloader = {
            param()
            $browser.FindElement([OpenQA.Selenium.By]::CssSelector($downloadSelector)).Click();
        }

        try {
            $downloader.Invoke();
        } catch {
            $browser.ExecuteScript("document.querySelector('$cookieBannerSelector').remove()");
            $downloader.Invoke();
        }
    }

    $file = Start-CustomDownload $context $url $action $tempDir;

    Start-Process -Wait -FilePath $file -ArgumentList "/S";
    Remove-Item -Recurse $tempDir;
}