@REM Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.
@echo off

setlocal
setlocal EnableDelayedExpansion

where pnputil
if %ERRORLEVEL% NEQ 0 echo "Missing pnputil in environment path" & goto :error

set OEM_INF=
set PREV_LINE=
for /f "delims=: tokens=2" %%A in ('pnputil /enum-drivers /class {4d36e97d-e325-11ce-bfc1-08002be10318}') do (
    set A=%%A
    set A=!A: =!
    if /i !A!==kipudrv.inf set OEM_INF=!PREV_LINE!
    set PREV_LINE=!A!
)
if not "%OEM_INF%"=="" (
    echo IPU driver is already installed.
    set UNINSTALL=y
    set /p "UNINSTALL=Do you want to uninstall the available driver and continue with this installation? [Y/n]: "
    if /i !UNINSTALL!==y (
        echo Uninstalling IPU driver by uninstalling "%OEM_INF%"
        powershell -command "dism /online /get-drivers /format:table | Select-String -Pattern $('(oem.*inf)(.+kipudrv\.inf.+)') | Foreach-Object { $oem, $rest = $_.Matches[0].Groups[1..2].Value; Write-Host $oem is a kipudrv.inf which will be deleted!!!; pnputil /delete-driver $oem /uninstall}"
        if %ERRORLEVEL% NEQ 0 echo Failed to uninstall "%OEM_INF%" & goto :error
    ) else (
        echo Exit without installing
        set errorlevel=1
        goto :error
    )
)

powershell -command "start-process PowerShell -verb runas -ArgumentList {"$signature = Get-AuthenticodeSignature kipudrv\kipudrv.cat"; "$store = Get-Item -Path Cert:\LocalMachine\Root"; "$store.Open('ReadWrite')"; "$store.Add($signature.SignerCertificate)"; "$store.Close()"; "$store = Get-Item -Path Cert:\LocalMachine\TrustedPublisher"; "$store.Open('ReadWrite')"; "$store.Add($signature.SignerCertificate)"; "$store.Close()";}"

pnputil -i -a kipudrv\kipudrv.inf
if %ERRORLEVEL% NEQ 0 echo "Failed to install kipudrv.inf file" & goto :error

PATH|find /i "C:\Windows\System32\AMD" >nul || setx PATH "C:\Windows\System32\AMD;%PATH%" /m
if %ERRORLEVEL% NEQ 0 echo "Failed to update system path" & goto :error

echo:
echo kipudrv.inf install successful

:error
exit /b %errorlevel%
