set -l dir (status dirname)

function runActionSetup -V dir
    source "$dir/hooks.fish"
    source "$dir/nix.fish"
    source "$dir/settings.fish"
    echo "Installing dependencies..."
    and runHook --force installValhallaDeps 'Please set up a function `installValhallaDeps` for installing `fish`, `git`, `jq`, `nix`, `ssh`, `sudo` and `tmux`.'
    and echo "Preparing nix..."
    and runHook prepareNix || installNixPkgs

    and echo "Flagging repository as safe..."
    and sudo git config --system --add safe.directory (realpath -m "$(status dirname)/../..")
    and runHook actionPreRun || true
end

function runActionConfigure -V dir
    and if [ -z "$CONFIG_NAME" ]
        source "$dir/settings.fish"
        selectProfile config
        set -gx CONFIG_NAME "$config"
    end
end

function disposeAction -V dir
    source "$dir/hooks.fish"
    source "$dir/nix.fish"
    runHook actionPostRun || true
    and uninstallNixPkgs
    and sudo git config --remove-section --system safe || true
end

function runAction -V dir
    runActionSetup
    and runActionConfigure
    and $argv
    and disposeAction
end

function runSetupUserAction -V dir
    source "$dir/settings.fish"
    runActionSetup
    runActionConfigure
    set -l name (getOSConfig setupUser.name)

    if [ "$USER" != "$name" ]
        set -l cmdline (cat /proc/$fish_pid/cmdline | string split0 || true)

        if [ (id -u) -ne 0 ]
            sudo --set-home --preserve-env env "PATH=$PATH" $cmdline
        else
            if [ -z "$TMUX" ]
                tmux new-session env (env) $cmdline
            else
                set -l sudoConfig "/etc/sudoers.d/PortValhalla"

                begin
                    set success true

                    if id -u "$name" &>/dev/null
                        echo "Setup user already exists!"
                    else
                        echo "Creating setup user"
    
                        and useradd \
                            --comment "PortValhalla Setup User" \
                            --system \
                            --groups nix-users \
                            --create-home \
                            --uid (getOSConfig setupUser.id --json) \
                            "$name"
                    end

                    and begin
                        echo "$name ALL=(ALL:ALL) NOPASSWD: ALL"
                    end >"$sudoConfig"

                    and sudo --preserve-env --set-home --user "$name" env "PATH=$PATH" $cmdline
                    or begin
                        read -P "An error occurred! Press enter to continue: "
                        set success false
                    end

                    disposeAction
                    rm "$sudoConfig"
                    userdel -rf "$name"
                    $success
                end
            end
        end
    else
        $argv
    end
end