. "$PSScriptRoot/../aliae/Manage.ps1";
. "$PSScriptRoot/../powershell/Profile.ps1";
. "$PSScriptRoot/../../Scripts/Software.ps1";
. "$PSScriptRoot/../../Types/InstallerAction.ps1";

Start-SoftwareInstaller @args `
    -Configurator {
        param([string] $Name)

        Add-PowerShellProfileStatement `
            -System `
            -Category "$Name" `
            -Script (
                @(
                    "# Oh My Posh!",
                    (Get-ScriptInitializer "oh-my-posh init pwsh"),
                    (Get-ScriptInitializer "oh-my-posh completion powershell")
                ) -join [System.Environment]::NewLine);
    } `
    -UserConfigurator {
        param(
            [hashtable] $Arguments
        )

        $user = $Arguments.Name;
        $theme = Get-UserConfig -UserName "$user" "programs.oh-my-posh.theme";

        function New-Theme {
            param($info)

            $root = "$(& {
                if ($IsWindows) {
                    sudo -u "$user" pwsh -c 'Write-Host $env:AppData';
                } else {
                    sudo -u "$user" bash -c 'realpath ~/.config';
                }
            })/oh-my-posh";

            $path = Join-Path $root "$($info.name).omp.json";
            $null = sudo -u "$user" pwsh -c New-Item -Force -ItemType Directory $root;

            sudo -u "$user" pwsh -CommandWithArgs 'Set-Content $args[0] -Value $args[1]' $path ([string](
                & {
                    if ($IsWindows) {
                        wsl cat $info.source | Out-String;
                    }
                    else {
                        Get-Content -Raw $info.source;
                    }
                }));

            return $path;
        }

        foreach ($additionalTheme in (Get-UserConfig -UserName "$user" "programs.oh-my-posh.additionalThemes")) {
            Write-Host "creating theme $additionalTheme";
            $null = New-Theme $additionalTheme;
        }

        if ($theme) {
            $varName = "POSH_THEME";

            if ($theme -isnot [string]) {
                $theme = [string](New-Theme $theme);
            }

            if ($IsWindows) {
                [System.Environment]::SetEnvironmentVariable($varName, $theme, "User");
            }
            else {
                . "$PSScriptRoot/../aliae/Manage.ps1";
                $value = $theme;
                $relativePath = sudo -u "$user" fish -c 'realpath --relative-base ~ $argv' $theme;

                if ($relativePath -ne $theme) {
                    $value = Join-Path "{{ .Home }}" $relativePath;
                }

                Add-EnvironmentVariable -User $Arguments.Name $varName $value;
            }
        }
    };