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

$null = New-Module {
    $path = "$env:LOCALAPPDATA/LGHUB";
    $softwareName = "LGHub";
    [string]$lghubPath;

    function Get-LogitechGHUBName() {
        return "lghub_system_tray.exe";
    }

    function Stop-LogitechGHUB() {
        [OutputType([string])]
        param();
        Write-Host "Killing Logitech G HUB process";
        $hubName = Get-LogitechGHUBName;
        $lghubPath = $(Get-Process | Where-Object { [System.IO.Path]::GetFileName($_.Path) -eq $hubName })[0].Path;

        $mainProcesses = Get-Process | Where-Object { @("lghub_agent.exe", $hubName) -contains [System.IO.Path]::GetFileName($_.Path) -and $(
            $_.Parent.ProcessName -eq "explorer" -or $null -eq $_.Parent) };

        $null = $mainProcesses | Foreach-Object { $_.Kill($true) };
        return $lghubPath;
    }

    function Backup-LogitechGHUB([Context] $context) {
        Write-Host "Backing Up Logitech G HUB";
        $hubPath = Stop-LogitechGHUB;

        Write-Information "Backing up important files";
        $context.Backup($path, $context.SoftwareArchive($softwareName), @("-i!settings.db", "-i!icon_cache"));

        if ($hubPath) {
            Write-Information "Restarting Logitech G HUB";
            Start-Process $hubPath;
        }
    }

    function Restore-LogitechGHUB([Context] $context) {
        Write-Host "Restoring Logitech G HUB";
        Write-Information "Installing the app";
        choco install -y --ignore-checksums lghub;
        $hubPath = Stop-LogitechGHUB;
        Write-Information "Removing existing settings";
        Remove-Item "$path/settings.*";
        Write-Information "Restoring important files";
        $context.Restore($context.SoftwareArchive($softwareName), $path);
        Write-Information "Deleting desktop icon";
        $context.RemoveDesktopIcon("*G HUB*");
        Write-Information "Restarting Logitech G HUB";
        Start-Process $hubPath;
    }
}