#!/bin/sh -e

##########################################################################
#   Script description:
#       Create a new user account on all nodes
#       
#   History:
#   Date        Name        Modification
#   2019-06-04  J Bacon     Begin (modified from cluster-useradd)
##########################################################################

usage()
{
    printf "Usage: $0 username uid primary-group-name gid 'Comment' shell max-password-age additional useradd flags]\n"
    exit 1
}


##########################################################################
#   Main
##########################################################################

if [ `id -un` != root ]; then                                                   
    printf "$0 must be run as root.\n"                                          
    exit 1                                                                      
fi                                                                              

if [ 0$1 = 0'--no-local-pw' ]; then
    no_local_pw=1
    shift
fi

if [ $# -lt 6 ]; then
    usage
fi

os_type=`auto-ostype`

user_name="$1"
user_id="$2"
group_name="$3"
gid="$4"
gecos="$5"
shell="$6"
shift; shift; shift; shift; shift; shift

# Create group if necessary
found_name=`awk -F : '$1 == "'$group_name'" { print $1 }' /etc/group`
if [ 0$found_name = 0$group_name ]; then
    printf "$group_name already exists.\n"
else
    printf "Creating $group_name\n"
    auto-add-group -g $gid $group_name
fi

# Create user
case $os_type in
DragonFly|FreeBSD)
    pw useradd $user_name -c "$gecos" -g $group_name -m \
	-s $shell -u $user_id $@
    ;;

NetBSD|OpenBSD|RHEL)
    useradd -c "$gecos" -g $group_name -m -s $shell -u $user_id $@ \
	$user_name
    ;;

*)
    auto-unsupported-os $0
    exit 1
    ;;

esac

if [ 0$no_local_pw = 01 ]; then
    auto-lock-local-pw $user_name
else
    printf "Set local password? [y]/n "
    read local_pw
    if [ 0$local_pw != 0n ]; then
	passwd $user_name
    else
	auto-lock-local-pw $user_name
    fi
fi
