#!/bin/bash

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

# (c) Antonio Sánchez León <introlinux[fix@]gmail[fix.]com>
# (c) Miguel Anxo Bouzada <mbouzada[fix@]gmail[fix.]com>
# (c) GALPon MinNo Team <minino[fix@]galpon[fix.]org>
# setember 2014

## -

case $LANG in
	ca*)
	TXTROOT="Has de executar aquest script amb «sudo»"
	TIT1="Sincronització d'equips"
	TIT2="Avís"
	WARN1="S'ha detectat la presència, en funcionament, del congelador d'escriptoris."
	WARN2="Aquesta aplicació de sincronització és incompatible amb la congelació d'escriptoris."
	WARN3="Encara que ambdues guarden una certa relació, el seu ús s'aplica a casuístiques molt diferents."
	WARN4="Si prefereixes fer servir aquesta sincronització, primer heu de desactivar la congelació."
	WARN5="S'abandona el procediment de sincronització."
	TIT3="Definir els equips de l'aula"
	TEXT1="Escull l'opció que determina la manera com vols sincronitzar els teus equips."
	TEXT2="Seguidament introdueix els números dels equips que vols sincronitzar.\n\tPer exemple: <i>102 104 165</i>\nSi deixes aquesta entrada en blanc es sincronitzaran tots els equips."
	TEXT3="Cal generar una llista dels equips de l'aula\nper accions futures de sincronització."
	TEXT4="Escriu en la casella els números dels equips separats\nper un espai,\n\tPer exemple: <i> 101 102 114 134 135 136</ie"
	TEXT5="Aquesta opció es guardarà a l'arxiu /opt/xarxaaula/LAN\ nper futurs canvis hauràs editar-ho manualment."
	MSG1="No hi ha cap equip que pugui ser sincronitzat."
	MSG2="Segur que està treballant en un S.O. <i>PicarOS</i> preparat per a l'aula d'informàtica?"
	MSG3="S'abandona el procés."
	FIELD1="Vull una sincronització"
	CBOX1a="GLOBAL"
	CBOX1b="tot l'entorn d'usuari"
	CBOX2a="BÀSICA"
	CBOX2b="tot excepte la carpeta personal"
	CBOX3a="PERSONAL"
	CBOX3b="només la carpeta personal"
	CBOX4a="CONFIGURACIONS"
	CBOX4b="només les configuracions"
	FIELD2="Equips a sincronitzar"
		;;
	es*)
		TXTROOT="Tiene que ejecutar este script con «sudo»"
		TIT1="Sincronización de equipos"
		TIT2="Aviso"
		TIT3="Definir los equipos del aula"
		TEXT1="Escoja la opción que determina la forma en que quiere sincronizar sus equipos."
		TEXT2="Seguidamente introduzca los números de los equipos que quiera sincronizar.\n\tPor ejemplo: <i>102 104 165</i>\nSi deja esta entrada en blanco se sincronizarán todos los equipos."
		TEXT3="Es necesario generar una lista de los equipos del aula\npara acciones futuras de sincronización."
		TEXT4="Escriba en el cajetín los números de los equipos separados\n por un espacio,\n\tPor ejemplo: <i>101 102 114 134 135 136</i>"
		TEXT5="Esta opción se guardará en el archivo /opt/redaula/LAN\npara futuros cambios deberá editarlo manualmente."
		MSG1="No hay ningún equipo que pueda ser sincronizado."
		MSG2="Seguro que está trabajando en un S.O. <i>PicarOS</i> preparado para el aula de informática ?"
		MSG3="Se abandona el proceso."
		FIELD1="Quiero hacer una sincronización"
		CBOX1a="GLOBAL"
		CBOX1b="todo el entorno de usuario"
		CBOX2a="BÁSICA"
		CBOX2b="todo excepto la carpeta personal"
		CBOX3a="PERSONAL"
		CBOX3b="sólo la carpeta personal"
		CBOX4a="CONFIGURACIONES"
		CBOX4b="sólo las configuraciones"
		FIELD2="Equipos a sincronizar"
		;;
	gl*)
		TXTROOT="Tiene que ejecutar este script con «sudo»"
		TIT1="Sincronización de equipos"
		TIT2="Aviso"
		TIT3="Definir los equipos del aula"
		TEXT1="Escoja la opción que determina la forma en que quiere sincronizar sus equipos."
		TEXT2="Seguidamente introduzca los números de los equipos que quiera sincronizar.\n\tPor ejemplo: <i>102 104 165</i>\nSi deja esta entrada en blanco se sincronizarán todos los equipos."
		TEXT3="Es necesario generar una lista de los equipos del aula\npara acciones futuras de sincronización."
		TEXT4="Escriba en el cajetín los números de los equipos separados\n por un espacio,\n\tPor ejemplo: <i>101 102 114 134 135 136</i>"
		TEXT5="Esta opción se guardará en el archivo /opt/redaula/LAN\npara futuros cambios deberá editarlo manualmente."
		MSG1="No hai ningún equipo que pueda ser sicronizado."
		MSG2="Seguro que está trabajando en un S.O. <i>PicarOS</i> preparado para aula informática ?"
		MSG3="Se abandona el proceso."
		FIELD1="Quiero hacer una sincronización"
		CBOX1a="GLOBAL"
		CBOX1b="todo el entrorno de usuario"
		CBOX2a="BÁSICA"
		CBOX2b="todo excepto la carpeta personal"
		CBOX3a="PERSONAL"
		CBOX3b="sólo la carpeta personal"
		CBOX4a="CONFIGURACIONES"
		CBOX4b="sólo las configuraciones"
		FIELD2="Equipos a sincronizar"
		;;
	*)	
		TXTROOT="You have to run this script with «sudo»"
		TIT1="Computer synchronization"
		TIT2="Warning"
		TIT3="Define the computers in the class"
		TEXT1="Choose the option that determines how you want to sync their computers."
		TEXT2="Then enter the numbers of the equipment you want to synchronize.\n\tFor example: <i>102 104 165</i>\nIf you leave this entry blank will synchronize all computers."
		TEXT3="We need to generate a list of computers in the classroom\nfor future synchronization actions."
		TEXT4="Write in the box the numbers of separate computers\n with a space.\n\tFor example: <i>101 102 114 134 135 136</i>"
		TEXT5="This option is stored in the /opt/redaula/LAN file\nfor future changes you will need to manually edit it."
		MSG1="There is no computer that can be synchronized."
		MSG2="Sure it is working on a S.O. <i> PicarOS </i> prepared for the computer room?"
		MSG3="The procedure is aborted."
		FIELD1="I want to sync"
		CBOX1a="GLOBAL"
		CBOX1b="entire user environment"
		CBOX2a="BASIC"
		CBOX2b="everything except the home folder"
		CBOX3a="PERSONAL"
		CBOX3b="only the home folder"
		CBOX4a="SETTINGS"
		CBOX4b="only settings in home"
		FIELD2="Computers to synchronize"
		;;
esac

[[ $(id -u) -ne 0 ]] && {
	echo
	echo "$TXTROOT"
	echo
	yad --button="gtk-close" \
		--window-icon="face-angry"\
		--image="face-angry" \
		--title="$TIT2" \
		--text="\n\t<span size='large' color='red'><b>$TXTROOT\t</b></span>"
	exit 1
}

[[ ! -d /opt/redaula ]] && {
	echo
	yad --button="gtk-close" \
		--window-icon="littlewizard"\
		--image="littlewizard" \
		--title="CONFIGURACIÓN DE AULA" \
		--text="\n\t<span size='large' color='red'><b>Es necesario configurar previamente la red local\n     con la herramienta Aula de informática\t</b></span>"
	exit 1
}



verificacion(){
	# ver se o usuário premeu en «Saír» ou no «X» da xanela
	ACCION="$?"
	test "$ACCION" -eq "1" || test "$ACCION" -eq "252"
	if [ "$?" -eq "0" ]; then
		exit
	fi
}

generaLAN(){
	LAN=$(yad --entry \
		--icon=dialog-question \
		--image=preferences-system-network \
		--title "${TIT3}" \
		--text "${TEXT3}\n\n${TEXT4}\n\n${TEXT5}")

	verificacion

	echo ${LAN} > /opt/redaula/LAN
}

#PONER LAN COMO "102 104 165" SIN INCLUIR LA IP DEL MAESTRO
#LAN="loqueseaquehayapuestoelusuario"

OPCION=$(yad \
	--icon=dialog-question \
	--image=preferences-system-network \
	--title "${TIT1}" \
	--text "${TEXT1}\n\n${TEXT2}" \
	--form --field="${FIELD1}:CB" \
		--field="${FIELD2}" \
			"${CBOX1a}: ${CBOX1b}!${CBOX2a}: ${CBOX2b}!${CBOX3a}: ${CBOX3b}!${CBOX4a}: ${CBOX4b}" )
			
# OPCION devuelve: Opción elegida con todo el texto|equipo equipo equipo|
# Por ejemplo: BÁSICA: todo excepto la carpeta personal|102 104 165|

verificacion

LAN=`echo ${OPCION}|cut -d"|" -f2`
MODO=`echo ${OPCION}|cut -d":" -f1`

if [ "$LAN" = "" ];then
	#MIRAMOS SI EL ARCHIVO /opt/redaula/LAN existe
	if [ -e /opt/redaula/LAN ];then
		LAN=`cat /opt/redaula/LAN`
		if [ "${LAN}" = "" ];then #si el archivo existe pero está vacío
			generaLAN
		fi			
	else
		generaLAN
	fi	

fi

# Si a pesar de todo sigue vacío...
if [ "${LAN}" = "" ];then
	LAN=`cat /opt/redaula/LAN`
	if [ "${LAN}" = "" ];then
		yad --button="gtk-close" \
			--window-icon="face-angry"\
			--image="face-angry" \
			--title="$TIT2" \
			--text="\n${MSG1}\t\n\n${MSG2}\t\n\n${MSG3}\n"
		exit 0
	fi
fi

	USUARIO=`who -m | awk '{print $1;}'`
	GATEWAY=`ip route | awk '/default/ { print $3 }'`
	IPLOCAL=`hostname -I`
	g1=`echo ${GATEWAY}|cut -d"." -f1`
	g2=`echo ${GATEWAY}|cut -d"." -f2`
	g3=`echo ${GATEWAY}|cut -d"." -f3`
	GATE=`echo $g1.$g2.$g3.`

sudo apt-get clean

sudo gobohide -f

#PASAMOS LAS LLAVES PARA ACCEDER SIN PASSWORD
# ESTO CON PASARLO UNA VEZ ES SUFI, PERO NO SABEMOS SI ALGÚN 
# EQUIPO SE RESTAURÓ O SE REPARÓ Y NO TIENE AÚN LAS LLAVES


for i in ${LAN};do

rm /tmp/pasakey

cat <<-EOF >/tmp/pasakey
#!/usr/bin/expect

spawn ssh-copy-id $GATE$i

expect {
    "*re you sure you want to continue connecting" {
        send "yes\r"
        exp_continue
    }
    "*assword*" {
        send "minino\r"
    exp_continue
    }
}
EOF

chmod +x /tmp/pasakey
sudo /tmp/pasakey

done



case $MODO in
	${CBOX1a}) 
		# OPCIÓN 1 TODO
		echo "Dentro"

		for i in ${LAN};do
			echo ""
			echo "Sincronizando equipo $i"
			mensaje "Sincronizador" "Sincronizando equipo $i" --icon=/usr/local/share/pixmaps/sincronizador.svg &

			echo ""
			sleep 2
			rsync -vaz  / root@$GATE$i:/ --delete --exclude 'root' --exclude 'SWAPFILE' --exclude 'usr/local/share/miniapps/Places/Compartida/AppRun' --exclude 'rc*' --exclude 'epoptes' --exclude 'redaula' --exclude 'default' --exclude 'home' --exclude 'boot' --exclude 'sys' --exclude 'dev' --exclude 'proc' --exclude 'tmp' --exclude 'run' --exclude '/etc/udev/*' --exclude 'blkid.tab' --exclude '/etc/exports' --exclude '/etc/hostname' --exclude '/etc/hosts' --exclude '/etc/NetworkManager/*' --exclude '/root/.ssh/*'

			rsync -vaz /home/ root@$GATE$i:/home/ --delete --exclude './config/autostart/epoptes-client.desktop' --exclude './config/autostart/nm-applet.desktop' --exclude '.gtk-bookmarks' --exclude '.Xauthority' --exclude '/home/Compartida' --exclude '.gvfs'
		done
		;;
	${CBOX2a}) 
		# OPCIÓN 2 TODO MENOS HOME
		for i in ${LAN};do
			echo ""
			echo "Sincronizando equipo $i"
			mensaje "Sincronizador" "Sincronizando equipo $i" --icon=/usr/local/share/pixmaps/sincronizador.svg &
			echo ""
			sleep 2
			rsync -vaz  / root@$GATE$i:/ --delete --exclude 'root' --exclude 'SWAPFILE' --exclude 'usr/local/share/miniapps/Places/Compartida/AppRun' --exclude 'rc*' --exclude 'epoptes' --exclude 'redaula' --exclude 'default' --exclude 'home' --exclude 'boot' --exclude 'sys' --exclude 'dev' --exclude 'proc' --exclude 'tmp' --exclude 'run' --exclude '/etc/udev/*' --exclude 'blkid.tab' --exclude '/etc/exports' --exclude '/etc/hostname' --exclude '/etc/hosts' --exclude '/etc/NetworkManager/*' --exclude '/root/.ssh/*'
		done
		;;
	${CBOX3a})
		# OPCIÓN 3 SÓLO CARPETAS PERSONALES
		for i in ${LAN};do
			echo ""
			echo "Sincronizando equipo $i"
			mensaje "Sincronizador" "Sincronizando equipo $i" --icon=/usr/local/share/pixmaps/sincronizador.svg &
			echo ""
			sleep 2
			rsync -vaz --filter='- .*' --ignore-errors /home/minino/* root@$GATE$i:/home/minino/
		done
		;;
	${CBOX4a})
		# OPCIÓN 4 SÓLO CONFIGURACIONES
		for i in ${LAN};do
			echo ""
			echo "Sincronizando equipo $i"
			mensaje "Sincronizador" "Sincronizando equipo $i" --icon=/usr/local/share/pixmaps/sincronizador.svg &
			echo ""
			sleep 2
			rsync -vaz --ignore-errors /home/minino/.??*  root@$GATE$i:/home/minino --delete --exclude './config/autostart/epoptes-client.desktop' --exclude './config/autostart/nm-applet.desktop' --exclude '.gtk-bookmarks' --exclude '.Xauthority' --exclude 'Compartida' --exclude '.gvfs'
		done
		;;
esac










 


#NOTAS

#SI RULA, PROBAR PONERLE UN & PARA QUE ACTUALICE A TODOS A LA VEZ
#ssh-keygen -t rsa (genera par de claves en el servidor)
# De esta forma no pregunta por el pass
#"  ssh-keygen -t rsa -f /root/.ssh/id_rsa -q -N ""

#ssh-copy-id root@IP (manda llave al cliente para acceder a él y decirle, hey!, que soy de confianza)
#el pasakey requiere de EXPECT
