#!/bin/bash
USER=$(whoami)
IP_ADDR=$(hostname -I | cut -d " " -f1)
OLD_NAME_SERVER=$( awk -F "=" '$1~/^host-name/ { print $2 }' /etc/avahi/avahi-daemon.conf) ## Nombre actual de la maquina como controlador
if test "$USER" = "root"; then
	if (yad --title "SERVIDOR EPOPTES" --text="<big>¿Quiere cambiar el identificador $OLD_NAME_SERVER de su equipo para epoptes?.</big>\n \
Recuerda que para \"vincular\" los clientes a éste servidor debes configurar en los mismos \n \
 * El <b>nombre</b> del servidor: $OLD_NAME_SERVER
o bien\n\
 * La <b>dirección IP</b>: $IP_ADDR\n\n\
<i>La opción de la IP puede ser la más fiable ya que nos aseguramos de que no hay otra máquina con la misma identificación o por filtros en la red</i>"\
	    --window-icon=vitalinux \
        --justify="center" --center --width="500" --height="200" \
		--button=gtk-ok:0 --button=gtk-cancel:1 ); then

		NEW_NAME_SERVER=$(yad --title "SERVIDOR EPOPTES" --entry --entry-text="$OLD_NAME_SERVER" --text "Escriba el nuevo nombre para éste equipo \(puedes dejarlo en blanco si vas a usar la dirección IP\)"\
			--window-icon=vitalinux \
			--width="550" --height="200" --center  --text-align="fill" --button=Hecho:0)
		[ "$?" != "0" ] && exit 1
		## Si se proporciona solo la IP quitar del daemon de avahi!!!
		if [ "${NEW_NAME_SERVER}" = "" ] ; then
			sed -i "s/.*host-name=.*/#host-name=/g" /etc/avahi/avahi-daemon.conf
			yad --title "SERVIDOR EPOPTES" --text "Recuerda que en los clientes debes proporcionar la IP <b>$IP_ADDR</b> del servidor"\
			--window-icon=vitalinux \
			--width="550" --height="200" --center --justify="center" --text-align="center" --button=Entendido:0
		else
			sed -i "s/.*host-name=.*/host-name=${NEW_NAME_SERVER}/g" /etc/avahi/avahi-daemon.conf
			yad --title "SERVIDOR EPOPTES" --text "En los clientes puedes proporcionar el nombre <b>$NEW_NAME_SERVER</b> o la IP <b>$IP_ADDR</b> del servidor"\
			--window-icon=vitalinux \
			--width="550" --height="200" --center --justify="center" --text-align="center" --button=Entendido:0
		fi
		service avahi-daemon restart 2>/dev/null
	else
			yad --title "Registro" --info --text "Se cancela la operación por el usuario..." \
				--window-icon=vitalinux \
				--width="350" --height="100" --center --justify="center" --text-align="center" --button=gtk-quit:1
	fi
fi
