#!/bin/env fish
set -l dir (status dirname)
source "$dir/../../lib/settings.fish"
set -l users (getUsers)

echo "Creating users..."

for name in (echo "$users" | jq '.[]' --raw-output0 | string split0)
    echo "Creating user `$name`..."

    function getUserInfo -V name -a config
        getUserConfig "$name" "$config" $argv[2..]
    end

    set -l groups (getUserInfo groups --apply 'builtins.concatStringsSep ","')
    set -l displayName (getUserInfo displayName --json)
    set -l shell (getUserInfo defaultShell --json)

    sudo useradd --create-home (
            if echo "$displayName" | jq --exit-status > /dev/null
                echo "--comment"
                echo "$displayName" | jq --raw-output
            end
        ) (
            if [ -n "$groups" ]
                echo "--groups"
                echo "$groups"
            end
        ) "$name"

    if echo "$shell" | jq --exit-status >/dev/null
        sudo chsh "$name" --shell (which (echo "$shell" | jq --raw-output))
    end

    echo "Please Choose a New Password for User `$name`"

    while ! sudo passwd "$name"
        echo "An error occurred! Please try again."
    end
end