#!/bin/bash
###########################################################################
#                                                                         #
# Copyright (C) 2017, Xunta de Galicia for Consolidación Software Abalar  #
# Project <software.libre@edu.xunta.es>                                   #
# Author: Gonzalo Vázquez Enjamio <gonzalo.vazquez.enjamio.sa@everis.com> #
# Modified by: Alfonso Bilbao Vélez <alfonso.bilbao.velez.sa@everis.com>  #
# Developed by EVERIS S.L.                                                #
#                                                                         #
###########################################################################
#*********************#
# VARIABLES ESTATICAS #
#*********************#
#RSYNC_REPO=puppet_ext
#RSYNC_REPO7=puppet_ext7
LOG_F=/var/log/syslog
RSYNC_SERVER=prd-rsync-0001.xunta.local
DNS_SERVER2=debian.uvigo.es
DNS_SERVER3=8.8.8.8

# Mensajes.
SIN_RED="Non hai conexion a internet. \n\nDeberias conectar o computador antes de continuar."

# Para comprobar ejecucion fuera de la red coorporativa.
#RSYNC_SERVER=1.1.1.1

#***********#
# FUNCIONES #
#***********#
# Chequear EXIT => !=0 salir
function check_exit(){
        if [ $? -ne 0 ];then
                /usr/bin/logger -p user.error -t puppet_rsync_background "Produciuse un erro durante a $PROCESO" 
		exit
        fi
}

# Comprobar conectividad a internet.
function check_conexion(){
	/bin/ping -c2 $DNS_SERVER3 2> /dev/null
        if [ $? -eq 0 ];then
		/usr/bin/logger -p user.info -t puppet_rsync_background "Equipo con conectividade de red."

	else
		/usr/bin/logger -p user.info -t puppet_rsync  "Equipo sin conectividade de red."
		exit
	fi
}

# Comprobar servidor al que conectarse.
function server_inout(){
	# Dentro de la red xunta.local.
    /bin/ping -c2 ${RSYNC_SERVER} 2> /dev/null

    if [ $? -eq 0 ];then
        SERVER=$(echo ${RSYNC_SERVER})

	# Fuera de la red coorporativa.
	else
		/bin/ping -c2 ${DNS_SERVER2} 2> /dev/null
		if [ $? -eq 0 ]; then
			SERVER=$(echo ${DNS_SERVER2})
		else
			/bin/ping -c2 ${DNS_SERVER2} 2> /dev/null
			if [ $? -eq 0 ]; then
				SERVER="$(dig +short ${DNS_SERVER2})"
			fi
		fi
    fi
}

# Seleccionar puppet_code.
function check_puppet_code(){
	DISTRO=$(lsb_release -c | awk '{print $2}')
	if [ "$DISTRO" = 'jessie' ];then 
		RSYNC_REPO='puppet_ext'
	else 
		RSYNC_REPO='puppet_ext7'
	fi  
}

# RSYNC puppet code.
function sincronizar(){
	 PROCESO="sincronización"
	 /usr/bin/logger -p user.info -t puppet_rsync_background "Comeza a sincronización."

	 /usr/bin/rsync -prlthz --chown=root:root --chmod=Du=rwx,Dgo=rx,Fu=rwx,Fgo=rx --contimeout=300 --info=progress2 --delete rsync://$SERVER/$RSYNC_REPO/ /opt/puppetlocal/ --log-file="$LOG_F"
	/usr/bin/logger -p user.info -t puppet_rsync_background "Sincronización finalizada con exito."
	check_exit
}

# Ejecutar puppet.
function puppetizar(){
	PROCESO="aplicación de cambios"
	/usr/bin/logger -p user.info -t puppet_rsync_background "Comeza a aplicación de cambios."
	if [ ${RSYNC_REPO} == 'puppet_ext' ];then
        /usr/bin/logger -t puppet_rsync_background "function puppetizar, valor de puppet_ext ${RSYNC_REPO}"
        # Ejecucion Maqueta Libre 17.
        /usr/bin/puppet apply -v /opt/puppetlocal/manifests/site.pp --manifestdir /opt/puppetlocal/manifests/ --modulepath /opt/puppetlocal/modules/ --fileserver /opt/puppetlocal/fileserver.conf -l syslog
		/usr/bin/logger -p user.info -t puppet_rsync_background "Cambios realizados con exito."
		check_exit
	else
        # Ejecucion Maqueta Libre 18.
		/usr/bin/puppet apply -v /opt/puppetlocal/manifests/site.pp --modulepath /opt/puppetlocal/modules/ -l syslog
	        /usr/bin/logger -p user.info -t puppet_rsync_background "Cambios realizados con exito."
	        check_exit
	fi
}

function advertencia(){
	/usr/bin/logger -p user.warning -t puppet_rsync_background "Non existe conexión co servidor rsync: $SERVER"	
}

#**************#
# FUNCION MAIN #
#**************#
main(){
	# Comprobar conectividade a internet.
	check_conexion

	# Comprobar servidor.
	server_inout
	/bin/ping -c2 $SERVER
	
	if [ $? -eq 0 ]; then
		if [ $SERVER == $RSYNC_SERVER ]; then
			/usr/bin/logger -p user.info -t puppet_rsync_background "Comeza o proceso de actualización en segundo plano."
			#Selección de puppet_code
			check_puppet_code

			# Sincronización
			sincronizar

			# Puppetización
			puppetizar
		else
            # Update.
			apt-get update

            # Seleccion puppet_code.
            check_puppet_code

            # Pupetizar.
			puppetizar
		fi

	else
        # Error. Leer advertencia.
		advertencia
	fi
}

main
