#!/bin/bash
#set -x
get_stack () {
	if [[ ! -z $1 && $1 == "wc" ]];then
		ls -I "*.sig" $registros | wc -l 
	else
		ls -I "*.sig" $registros | tail -1
	fi
}

# Generar una llave privada ECDSA si no existe
generate_private_key () {
  test -f "$private_key" && return 1

  ssh-keygen -t ecdsa -f "$private_key" -N "" -C "$@"
}

# Firmar el archivo usando la llave privada.
#
# Uso: sign_file archivo.json
# Devuelve: La firma
sign_file () {
  local _file="$1"

  test ! -f "$_file" && return 1
  test -f "$_file.sig" || ssh-keygen -Y sign -f "$private_key" -n file "$_file"  >/dev/null 2>&1
  cat "${_file}.sig" | grep -v SIGNATURE | tr -d "\n"
}


funcion_datos_simulados() {
	
	lecturas="id:dummy_plug-01 tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-02 tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-03 tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 AD_ARDUINO id:dummy_plug-04 tp:temp vl:$(( $RANDOM % 20 + 15 )) un:C er:99 AD_SENSOR tp:hum vl:$(( $RANDOM % 50 + 35 )) un:percent er:99 END"

}

funcion_datos_sensores() {

	peticiones=1
	arduinos=( 1 2 )
	for arduino_id in ${arduinos[@]};do
	lectura_arduino=($(timeout 3 $arduinos_py $arduino_id))

	let "bloques = (${#lectura_arduino[@]} - 1) / 4"

	#lecturas="$lecturas id:${lectura_arduino[0]}"
	lecturas="$lecturas id:${arduino_id[0]}"

	indice=1
	vueltas=1

	while [ $vueltas -le $bloques ]; do

		lecturas="$lecturas tp:${lectura_arduino[$indice]} vl:${lectura_arduino[$(expr $indice + 1 )]} un:${lectura_arduino[$(expr $indice + 2 )]} er:${lectura_arduino[$(expr $indice + 3 )]}"

		if [ $vueltas -lt $bloques ]; then
			lecturas="$lecturas AD_SENSOR"
		fi	

		let "indice = $indice + 4 "

		((vueltas++))
	done

	if [ $peticiones -lt ${#arduinos[@]} ];then
		lecturas="$lecturas AD_ARDUINO"
	fi
	((peticiones++))

	
done
lecturas="$lecturas END"
}



funcion_configurar() {
	local comando=$1
	local parametro=$2
	local parametros=$*
	local url_regex='(https?|HTTPS?)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]'
	local nuevo_modo='(test|sensores)'

case $comando in
	nombre)
                while :;do
			nuevo_nombre=$(echo $parametros | sed 's/nombre //g' | sed 's/ /_/g')

		        if [[ "$nuevo_nombre" =~ ^[a-zA-Z0-9_]+$  ]];then
		 		sed -i 's/nombre='$nombre'/nombre='$nuevo_nombre'/' $config
				echo "nombre: $nuevo_nombre"
				break
		        else
		                echo "El nombre solo puede contener carateres alfanumericos."
				read -p "nombre: " parametro
		        fi
		done
	        ;;

	servidor)
                while :;do
                        if [[ $parametro =~ $url_regex ]]; then
                                sed -i 's}servidor='$servidor'}servidor='"$parametro"'}' $config
                                echo "Servidor $parametro"
                                break
                        else
                                echo "Intruzca una url válida."
                                read -p "url: " parametro
                        fi
                done
		;;

	intervalo)
		while :;do
			if [[ $parametro -ge 1 && $parametro -le 60 ]]; then
				sed -i 's/intervalo=[0-9]*/intervalo='$parametro'/' $config
                		echo "Intervalo seteado en $parametro"
				echo "Para aplicar los cambios ejecute
					sudo nodemecu captura dentener
					sudo nodemecu captura iniciar"
				break
	        	else
        	        	echo "Establezca un valor entre 1 y 60."
				read -p "Intervalo: " parametro
	        	fi
		done
		;;
	modo)
		while :;do
			if [[ $parametro =~ $nuevo_modo ]]; then
				sed -i 's/modo='$modo'/modo='$parametro'/' $config
				break
			else
				echo "Los modos posibles son 'test' y 'sensores'"
				read -p "modo: " parametro

			fi

		done
esac
}


funcion_captura() {
	

	if [ "$1" = "iniciar" ]; then 

		echo "Iniciando la captura de datos en modo '$modo'"
		echo ""
		read -p "Desea continuar? Presione 'enter' para continuar o 'ctrl-c' para cancelar..."
		echo "*/$intervalo * * * * $directorio_instalacion/generador_json" > /tmp/nodemecu.crontab
		crontab -u root /tmp/nodemecu.crontab
		echo ""
		echo "Se tomarán datos cada $intervalo minutos."
		echo ""
		exit
	elif [ "$1" = "detener" ]; then
		crontab -u root -r
		echo "Se detuvo la toma de datos."
		echo ""
	else
		echo "Ingrese una orden válida: 'iniciar' o 'detener'."

	fi
}


### Validaciones

test_conf_nombre() {

	if [ -z $nombre ]; then
		echo "No se establecio un nombre para el dispositivo."
		return 1
	fi
}


test_conf_servidor () {

	if [ -z $servidor ];then
		echo "No se establecio un servidor de entrega."
		return 1
	fi
}

test_conf_intervalo() {

	if [ -z $intervalo ];then
		echo "No se establecio un intervalo de captura."
		return 1
	fi
}

test_conf_key() {

	if [ ! -f $private_key ];then
	       	echo "No se creo juego de llaves."
		return 1
	fi
}




funcion_validador_json() {
	
	validar="$@"

	echo $validar | jsonlint-php > /dev/null 2>&1 || return 1
}

funcion_verificar_internet() {

	if host fsf.org > /dev/null 2>&1; then
		return 0
	else
		return 1
	fi

}

funcion_espera() {
	sleep 1m
	#sleep ${intervalo:-1}m

}


funcion_envio_registro() {

		curl -s --show-error -w "~%{http_code}" \
			-X POST -H "X-Signature: $(sign_file $registros/$file)" \
			-H "Content-Type: application/json" -d @$registros/$file \
			$servidor 2> $curl_err

}


funcion_monitor() {
	local sb="\x1b["
	local eb="\x1b[K\x1b[0m"
	local st="\e["
	local et="\e[0m"

	while :;do
		clear
		echo -e "${sb}1;44;97m Nodemecu Monitor${eb}"
		echo ""
		echo -e "${st}1;94mNombre:${et} $nombre ${st}1;94mServidor:${et} $servidor ${st}1;94mIntervalo:${et} $intervalo"
		echo ""
		echo -e "${sb}1;44;97m Registros${eb}"
		echo ""
		echo -e "En cola: $(ls -I *.sig $registros| wc -l)"
		echo -e "Enviados: $(ls -I *.sig $historicos | wc -l)"
		echo -e "Registros corrupts: $(ls -I *.sig $registros_corruptos | wc -l)"
		echo ""
		echo -e "${sb}1;44;97m Ultimos mensajes${eb}"
		echo ""
		echo -e ${st}1m"Systemd unit 'nodemecu.service'${et}"
		journalctl -n 3 -u nodemecu
		echo ""
		echo -e ${st}1m"Fichero '$log'${et}"
		cat /var/log/nodemecu_errors.log | grep -v "Salida de curl" | grep -v '[*<>{}]' | tail -3

		sleep 2 
	done

}

