#!/bin/sh
#
# livecd-user	Create LiveCD user
#
# chkconfig: 345 06 94
# description:	Create LiveCD user

# Do not load RH compatibility interface.
WITHOUT_RC_COMPAT=1

# Source function library.
. /etc/init.d/functions

LOCKFILE=/run/lock/subsys/livecd-user
RETVAL=0

. /etc/sysconfig/livecd-user.conf

LIVECD_LOGIN="${LIVECD_LOGIN?Variable is not defined}"
LIVECD_GROUPS="${LIVECD_GROUPS:-}"
LIVECD_ADMIN="${LIVECD_ADMIN:-}"
LIVECD_SUDO="${LIVECD_SUDO:-}"

add_user() {
	useradd -m "$1" &&
	usermod -p "" "$1" &&
	if [ -n "$LIVECD_GROUPS" ]; then	# some of them might be missing
		local group=
		for group in $LIVECD_GROUPS; do
			usermod -a --groups "$group" "$1" ||:
		done
	fi
}

set_password() { echo "$1:$2" | chpasswd; }

set_admin() { usermod -a --groups "wheel" "$1"; }

# NB: one must care to purge this from LiveCD if it's installed permanently
set_sudo() {
	[ ! -w "/etc/sudoers" ] ||
		echo "$1	ALL=(ALL) ALL" >> "/etc/sudoers"
}

create_livecd_user()
{
	echo -n "Create LiveCD user '$LIVECD_LOGIN'"

	add_user "$LIVECD_LOGIN"
	[ -z "$LIVECD_ADMIN" ] || set_admin "$LIVECD_LOGIN"
	[ -z "$LIVECD_SUDO" ] || set_sudo "$LIVECD_LOGIN"

	echo "Hello friend, say '$LIVECD_LOGIN' to log in at \\l" >> /etc/issue

	# configure hasher and gear, if builder-useradd is available
	BUILDER_USERADD=builder-useradd
	if command -v $BUILDER_USERADD >/dev/null 2>&1; then
		$BUILDER_USERADD "$LIVECD_LOGIN"
	fi

	# configure autologin
	. autologin-sh-functions
	al_enable "$LIVECD_LOGIN"
}

start()
{
	getent passwd "$LIVECD_LOGIN" >/dev/null || create_livecd_user

	RETVAL=$?
	[ $RETVAL = 0 ] && echo_success || echo_failure
	return $RETVAL
}

# See how we were called.
case "$1" in
	start|restart|reload)
		start
		;;
	stop)
		;;
	condstop)
		;;
	condrestart|condreload)
		if [ -e "$LOCKFILE" ]; then
			start
		fi
		;;
	status)
		;;
	*)
		msg_usage "${0##*/} {start|stop|reload|restart|condstop|condrestart|condreload|status}"
		RETVAL=1
esac

exit $RETVAL
