#!/bin/env fish
begin
    set -l dir (status dirname)
    source "$dir/../../Scripts/software.fish"

    function configureSW -V dir
        source "$dir/../bash/profile.fish"
        source "$dir/../fish/profile.fish"
        set -l file (pwsh -CommandWithArgs '. $args[0]; Get-GlobalConfigPath' "$dir/Constants.ps1");
        sudo install -Dm644 "$dir/aliae.yml" "$file"

        begin
            printf %s\n \
                "if [ -f $(string escape $file) ]" \
                'then' \
                "  eval \"\$(aliae init bash --config $(string escape $file))\"" \
                'fi' \
                '' \
                'if [ -n "$ALIAE_CONFIG" ] && [ -f "$ALIAE_CONFIG" ] || [ -f ~/.aliae.yaml ]' \
                'then' \
                '  eval "$(aliae init bash)"' \
                'fi' \
                '' \
                'eval "$(aliae completion bash)"'
        end | installBashProfile "aliae" "aliae"

        if type -q fish
            begin
                printf %s\n \
                    "if [ -f $(string escape $file) ]" \
                    "  eval \"\$(aliae init bash --config $(string escape $file))\"" \
                    'end' \
                    '' \
                    'if [ -n "$ALIAE_CONFIG" ] && [ -f "$ALIAE_CONFIG" ] || [ -f ~/.aliae.yaml ]' \
                    '  aliae init fish | source' \
                    'end' \
                    '' \
                    "aliae completion fish | source"
            end | installFishProfile "aliae" "aliae"
        end

        sudo -HE pwsh "$dir/Main.ps1" Configure
    end

    function userConfig -V dir -a user
        pwsh -CommandWithArgs '& $args[0] ConfigureUser @{ name=$args[1]; }' "$dir/Main.ps1" $user
    end

    runInstaller $argv
end