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`, `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 "$(status dirname)/../..")
    and runHook actionPreRun || true
end

function runActionConfigure
    and if [ -z "$CONFIG_NAME" ]
        selectProfile config
        set -x 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
    if [ (id -u) -eq 0 ]
        set -l cmdline (cat /proc/$fish_pid/cmdline | string split0)

        if [ -z "$TMUX" ]
            runActionSetup
            tmux new-session -e "CONFIG_NAME=$CONFIG_NAME" $cmdline
        else
            source "$dir/settings.fish"
            runActionConfigure
            set -l sudoConfig "/etc/sudoers.d/PortValhalla"
            set -l name (getOSConfig setupUser.name)

            and begin
                echo "Creating setup user"

                and useradd \
                    --comment "PortValhalla Setup User" \
                    --system \
                    --no-user-group \
                    --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" $cmdline
            disposeAction
            rm "$sudoConfig"
            userdel -rf "$name"
        end
    else
        $argv
    end
end