#!/bin/bash

set -e

USERNAME=pletestkylin111
PASSWORD=Kylin123.
AUTO_LOGIN=1
KUID=11111
# sudo 免密
echo "pletestkylin111 ALL=(ALL) NOPASSWD: ALL" >/target/etc/sudoers.d/pletestkylin111

data_unformat=false
echo "s1=$1"
if [[ "$1" == "true" ]]; then
	if [[ -f /target/etc/passwd ]]; then
        	user_names=
                user_names=`cat "/target/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
                                	data_unformat=true
                                fi
                                done
                fi
        fi
fi

if [[ "$data_unformat" == "false" ]]; then
	echo "设置用户 ${USERNAME}"
	chroot /target useradd -u ${KUID} -m -s /bin/bash "${USERNAME}"
	chroot /target sh -c "echo ${USERNAME}:${PASSWORD} | chpasswd"
fi

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

set_autologin() {
    if [[ "${AUTO_LOGIN}" == "1" ]]; then
        if [[ -d /target/etc/lightdm ]]; then
            # Configure LightDM autologin
            LightDMCustomFile=/target/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}
            # 设置 test 自动登录
            else
                sed -i "s/^autologin-user=.*$/autologin-user=${USERNAME}/g" ${LightDMCustomFile}
            fi
        fi
    fi
}

if [[ "$data_unformat" == "false" ]]; then
	add_groups
	set_autologin
fi

if grep -qE 'ple-mode' /proc/cmdline; then
	if [[ -f /target/etc/apt/sources.list ]]; then
   		mv /target/etc/apt/sources.list /target/etc/apt/sources.list.bc
	fi

	if [[ -f /target/etc/apt/sources.list.ple ]]; then
    		mv /target/etc/apt/sources.list.ple /target/etc/apt/sources.list
    		chroot /target apt-get update --allow-insecure-repositories -y
	fi

	chroot /target /bin/sh -c "unset DEBIAN_HAS_FRONTEND && apt-get install -y --allow-unauthenticated  kylin-audit-mode"

	if [[ -f /target/etc/apt/sources.list.bc ]]; then
    		mv /target/etc/apt/sources.list.bc /target/etc/apt/sources.list
    		chroot /target apt-get update --allow-insecure-repositories -y
	fi
fi
