#!/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

    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="alumno"
    # Lo añadimos al grupo nopasswdlogin para no requerir password para iniciar sesion:
    # LISTA_GRUPOS_SECUNDARIOS=("alumno" "dialout" "cdrom" "audio" "video" "nopasswdlogin")
    LISTA_GRUPOS_SECUNDARIOS=("dialout" "cdrom" "audio" "video")
    PASS="estudiante"
    COMENTARIO="${NOMBRE} - IES Mar de Aragón (Taller 17B)"
    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

    # Reseteamos la password del usuario para que la pueda cambiar en el primer inicio de sesión, para usuario que no son de examen:
    getent passwd "${NOMBRE}" &>/dev/null &&
        chage -d 0 "${NOMBRE}" &&
        echo "=> Se ha reseteado la password: ${NOMBRE}"

    # 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
