#!/bin/bash

set -e

if [[ "${is_minimal}" = "true" ]]; then
    return 0
elif [[ "${is_ghost}" = "true" ]]; then
    return 0
fi

USERNAME=$(get_value username1)
PASSWORD=$(get_value_bytearray password1)
AUTO_LOGIN=$(get_value autologin)
KUID=1002

if [[ -n "${USERNAME}" ]] && [[ -n "${PASSWORD}" ]]; then
	data_unformat=$(get_value data-unformat)
	if [[ "${data_unformat}" == "true" ]]; then
		if [[ -f /etc/passwd ]]; then
			user_names=
			user_names=`cat "/etc/passwd" | grep home | grep "/bin/bash"`
			if [[ -n "${user_names}" ]]; then
        			for i in ${user_names}; do
                			user_name=${i%%:*}
                			echo "${user_name}"
					if [[ "${user_name}" == "${USERNAME}" ]]; then
						return 0
					fi
        			done
			fi
		fi
	fi
else
	return 0
fi

msg "start to create first user"	

msg "设置用户 ${USERNAME}"
useradd -m -s /bin/bash -u ${KUID} "${USERNAME}"
usermod -c "${USERNAME}" "${USERNAME}"
echo "${USERNAME}:${PASSWORD}" | chpasswd
# /etc/sudoers

add_groups() {
    user_default_groups=(adm cdrom sudo dip plugdev users lpadmin sambashare debian-tor libvirtd lxd)
    for group in ${user_default_groups[*]}; do
        adduser ${USERNAME} $group || true
    done
}

set_autologin() {
    if [[ "${AUTO_LOGIN}" = "1" ]]; then
        if [[ -d /etc/lightdm ]]; then
            # Configure LightDM autologin
            LightDMCustomFile=/etc/lightdm/lightdm.conf
            AutologinParameters="autologin-guest=false\n\
autologin-user=${USERNAME}\n\
autologin-user-timeout=0"
        if ! grep -qs '^autologin-user' ${LightDMCustomFile}; then
                if ! grep -qs '^\[Seat:\*\]' ${LightDMCustomFile}; then
                    echo '[Seat:*]' >>${LightDMCustomFile}
                fi
                sed -i "s/\[Seat:\*\]/\[SeatDefaults]\n${AutologinParameters}/" ${LightDMCustomFile}
            # oem config scenario
            else
                #sed -i "s/^\(\(str  *\)\?autologin-user\)=.*$/\1=${USERNAME}/g;" /etc/lightdm/lightdm.conf
                sed -i "s/^autologin-user=.*$/autologin-user=${USERNAME}/g" ${LightDMCustomFile}
            fi
        fi
	systemctl restart accounts-daemon.service || true
    fi
}

add_groups

set_autologin


