#!/bin/bash
set -euo pipefail

if [ "$(id -u)" != '0' ]; then
	echo 'You must be root to run this script'
	exit 1;
fi

read -r -p 'Do you want to create a system user?[Y/n] ' answer
case "${answer}" in
	[nN])
		readonly system=no
		;;
	[yY]|'')
		readonly system=yes
		;;
	* )
		echo 'Answer not valid. Aborting'
		exit 1
		;;
esac

read -r -p 'Enter username ' username
read -r -p 'Enter additional groups, as a comma separated list with no spaces.[] ' groups
#create home?
if [ "${system}" = yes ] ; then
	readonly default_home_prompt="[y/N]"
	readonly default_home=no
else
	readonly default_home_prompt="[Y/n]"
	readonly default_home=yes
fi
read -r -p "Create user home directory?${default_home_prompt} " answer
case "${answer}" in
	[yY])
		readonly home=yes
		;;
	[nN])
		readonly home=no
		;;
	'')
		readonly home=${default_home}
		;;
	*)
		echo 'Answer not valid. Aborting'
		exit 1
		;;
esac
#Login shell
if [ "${system}" = yes ] ; then
	readonly default_shell='/usr/sbin/nologin'
else
	readonly default_shell='/bin/bash'
fi
read -r -p "Enter the user login shell.[${default_shell}] " shell
if [ -z "${shell}" ] ; then
	shell=${default_shell}
fi

command="adduser"
if [ "${system}" = yes ] ; then
	command="${command} --system"
fi
if [ "${home}" = no ] ; then
	command="${command} --no-create-home"
fi


${command} --shell "${shell}" "${username}"
if [ -n "${groups}" ] ; then
	usermod --groups "${groups}" "${username}"
fi

echo "Run passwd ${username} in order to change the password for the new user"
