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

function configureNix -V dir
    source "$dir/../Software/nix/main.fish" configure user
end

if [ (id -u) -eq 0 ]
    configureNix
    set -l name (getConfig valhalla.setupUser.name)
    set -l sudoConfig "/etc/sudoers.d/PortValhalla"

    runHook createUser || \
        begin
            useradd \
                --comment "PortValhalla setup user" \
                --system \
                --no-user-group \
                --groups wheel,nix-users \
                --create-home \
                --uid (getConfig valhalla.setupUser.id --json) \
                "$name"
        end

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

    and sudo --preserve-env="CONFIG_MODULE" --user "$name" "$INSTALLER_SCRIPT"
    rm "$sudoConfig"
    userdel -r "$name"
else
    configureNix
    source "$dir/../Software/bash/main.fish"
    runHook initialize || true
    runHook installDrivers || true
    runHook installOS || true

    runHook addUsers || begin
        source "$dir/users.fish"
    end

    runHook installSoftware || true
    runHook initializeConfig || true

    runHook postInstall || true
end