#!/bin/sh

. /lib/functions.sh

add_system_shells() {
	system_shells=$(cat /etc/shells)
	for line in $system_shells
	do
		if [ "${line}" = "/bin/ash" ]; then
			continue
		fi

		shell_name=$(basename "${line}")
		# Add the shell in UCI if not exists
		sec=$(uci -q show users | grep -E "^users\.@shell\[[0-9]+\]\.name=\'$shell_name\'$")
		if [ -z "${sec}" ]; then
			sec="shell_${shell_name}"
			uci -q set users."${sec}"=shell
			uci -q set users."${sec}".name="${shell_name}"
			uci -q set users."${sec}.enabled=1"
		fi
	done
}

#Now remove the shell from users if assigned
remove_user_shell() {
	local shell
	config_get shell "$1" shell ""

	if [ -n "${shell}" ]; then
		if [ "${shell}" = "${2}" ]; then
			uci -q set users."${1}.shell="
		fi
	fi
}

# Now remove non existing shell from UCI
remove_shell() {
	local name
	local exist=0
	config_get name "$1" name ""
	system_shells=$(cat /etc/shells)

	if [ -n "${name}" ]; then
		# Remove if not exist in system
		exist=0
		for line in $system_shells
		do
			shell=$(basename "${line}")
			if [ "${shell}" = "${name}" ]; then
				exist=1
				break
			fi
		done

		if [ "${exist}" -eq 0 ]; then
			uci -q delete users."$1"
			# Remove this shell from users if assigned
			config_foreach remove_user_shell user "${name}"
		fi
	fi
}

config_load users
add_system_shells
config_foreach remove_shell shell

# Remove ash
uci -q delete users.shell_ash

exit 0
