#!/bin/bash

# desc: Recibimos como parámetros la lista de usuarios a crear, separados por ":" cuando el idioma del sistema es diferente del español
# Los usuarios no necesitan escribir contraseña para iniciar sesión gráfica

for USUARIO ; do
    # Deshabilitamos el inicio de sesión automático: (lo deshabilitamos vía vx-centro.conf.json)
    # vx-funcs-users vx-usuario_inicio_deshabilitado
    FICHERO="/etc/lightdm/lightdm.conf"
    if grep -q "autologin-user=" "${FICHERO}" > /dev/null 2> /dev/null ; then
        sed -i "s/^autologin-user=.*/autologin-user=SIN-INICIO-AUTOMATICO/g" "${FICHERO}"
    else
        echo "autologin-user=SIN-INICIO-AUTOMATICO" >> "${FICHERO}"
    fi
    
    NOMBRE="${USUARIO%:*}"
    # Comprobamos si el usuario ya existe:
    vx-funcs-users vx-check_exit_users "${NOMBRE}" && \
    {
        echo "El usuario ya existe: ${NOMBRE}" ;
        continue ;
    }
    echo "${USUARIO}" | grep -q ":" && IDIOMA="${USUARIO#*:}" || IDIOMA="es"
    # echo "Se creará ${USUARIO}: Nombre => ${NOMBRE} Idioma => ${IDIOMA}"
    SHELL="/bin/bash"
    HOMEUSU="/home/${NOMBRE}"
    GPRIMARIO="${NOMBRE}"
    # Lo añadimos al grupo nopasswdlogin para no requerir password para iniciar sesion:
    LISTA_GRUPOS_SECUNDARIOS=("alumno" "dialout" "cdrom" "audio" "video" "nopasswdlogin")
    PASS="alumno"
    COMENTARIO="${NOMBRE} - IES Miguel Servet (alumno)"
    vx-funcs-users vx-check_exit_groups "${GPRIMARIO}" || \
    groupadd "${GPRIMARIO}"
    if useradd -c "${COMENTARIO}" \
    -s "${SHELL}" \
    -m -d "${HOMEUSU}" \
    -g "${GPRIMARIO}" \
    -G "$(echo "${LISTA_GRUPOS_SECUNDARIOS[*]}" | tr -s " " ",")" \
    -p "$(mkpasswd -s -m sha-512 "${PASS}")" \
    "${NOMBRE}" ; then
        vx-funcs-bash vx-echo_log_ok "=> Se ha creado el usuario ${NOMBRE}"
    else
        vx-funcs-bash vx-echo_log_error "=> Problemas creando el usuario ${NOMBRE}"
    fi
    # Configuramos el idioma del usuario:
    case "${IDIOMA}" in
        "es" ) IDIOMA="es_ES:es_ES.UTF-8"
        ;;
        "en" ) IDIOMA="en:en_GB.UTF-8"
        ;;
        "fr" ) IDIOMA="fr_FR:fr_FR.UTF-8"
        ;;
    esac
    LENGUAJE="${IDIOMA%:*}"
    # Eliminamos el prefijo hasta el ":":
    FORMATOLOCAL="${IDIOMA#*:}"
    if vx-funcs-users vx-conf_idioma_usuario "${NOMBRE}" "${LENGUAJE}" "${FORMATOLOCAL}" ; then
        vx-funcs-bash vx-echo_log_ok "¡¡Ok!! Se han configurado el idioma: ${NOMBRE} ${IDIOMA}"
    else
        vx-funcs-bash vx-echo_log_error "¡¡Error!! Problemas para para configurar el idioma: ${NOMBRE} ${IDIOMA}"
    fi
    
done