#!/bin/bash

. /usr/lib/eole/diagnose.sh
. /usr/lib/eole/ihm.sh

# Load configuration
. /etc/eole/eole-ltsp.conf

spinner(){
    # to use it call a long task, background it and call spinner on it's pid
    # (long_long_task) &
    # spinner $!
    local pid=$1
    local delay=5
    while ps --no-headers --pid "${pid}" > /dev/null 2>&1 ; do
        echo -n '.'
        sleep $delay
    done
    echo
}

sed -i 's/^PasswordAuthentication no/PasswordAuthentication yes/;
        s/^AllowUsers/#AllowUsers/;
        s/^AllowGroups/#AllowGroups/;
        s/^AllowTcpForwarding no/AllowTcpForwarding yes/' \
        /etc/ssh/sshd_config

systemctl restart ssh

# FIXME: intall manually but should be done at least in dictionnary
xdesktop="${BUREAU_GRAPHIQUE_THIN}"

if [ $xdesktop = "mate" ];then
    echo "Configuration du bureau MATE"
    update-alternatives --set x-session-manager /usr/bin/mate-session 2>&1 >/dev/null
else
    echo "Configuration du bureau XFCE"
    update-alternatives --set x-session-manager /usr/bin/startxfce4 2>&1 >/dev/null
fi

#Create /opt/nbd-swap with correct permissions
if ! [ -d /opt/nbd-swap ];then
    mkdir /opt/nbd-swap
fi
chown nbd: /opt/nbd-swap

# Do nothing if the IP is not defined (AmonEcole-Eclair)
if [ -n "${ADRESSE_SERVEUR_NFS}" ]
then
    if ! egrep -q nfs /etc/modules;then
        echo nfs4 >> /etc/modules
        #Si nfs pas dans /etc/modules alors il n'est pas chargé
        modprobe nfs4
    fi
    nfs_fstab_line="${ADRESSE_SERVEUR_NFS}:/home /home nfs4 auto,nouser,rsize=8192,wsize=8192,timeo=14,intr,acl,nolock,async,clientaddr=${ADRESSE_IP_ETH0} 0 0"

    if ! egrep -q 'nfs' /etc/fstab ;then
        echo ${nfs_fstab_line} >> /etc/fstab
    else
        #Attention / ne convient pas comme separateur sed
        sed  -i "s%^\d*.* /home nfs*.*$%${nfs_fstab_line}%" /etc/fstab
    fi

    if TestService nfs ${ADRESSE_SERVEUR_NFS}:2049 >/dev/null 2>&1; then
        if ! mount |egrep -q '^${ADRESSE_SERVEUR_NFS}'; then
            mount /home
        fi
    else
        EchoRouge "Le serveur NFS (${ADRESSE_SERVEUR_NFS}) ne semble pas joignable"
    fi
fi

#We need fuse group on the server...
if ! egrep -q fuse /etc/group;then
    addgroup fuse > /dev/null 2>&1
fi

# and /dev/fuse writebale by fuse group
chgrp fuse /dev/fuse > /dev/null 2>&1
chmod g+rw /dev/fuse > /dev/null 2>&1

#admin devrait être membre du groupe lpadmin
# ref #20746, #28352
if ! [ -n "$(id admin | grep lpadmin)" ];then
    addgroup admin lpadmin
fi

IMAGE_DEFAULT="${LTSP_CLIENT_TYPE}_${LTSP_CLIENT_ARCH}"
DEFAULT_TFTPBOOT_DIR="${REPERTOIRE_TFTP}/${IMAGE_DEFAULT}"

EchoVert "Création du lien symbolique pour l'image par défaut"
ln -snf "$IMAGE_DEFAULT" "${REPERTOIRE_TFTP}/default"
