#!/bin/bash

# script to get stats from all computers
# spd at daphne.cps.unizar.es
# Mon Nov  9 13:50:00 CET 2026

#
# intended to run from cron
#
# */20 * * * * /usr/bin/flock -n /var/run/og_stats.lock /usr/local/sbin/ogstats.sh >> /var/log/ogstats.log 2>&1
#

source <(sudo awk -F\; '
		/cnx=/ {
			printf("USER=%s\n", $2);
			printf("MYSQL_PWD=%s\n", $3);
			printf("DB=%s\n", $4);
		}
	' /opt/opengnsys/www/controlacceso-*.php)

export MYSQL_PWD
CTIMEOUT=1

# filter out unwanted or dummy "aulas"
filter()
{
	# cat
	egrep '^L[0-9T]' | grep -v "L1.04"
}


###########################################################################
#
# get aulas
#

declare -a aulas
declare -a idaulas

while read a i
do
	aulas+=("$a")
	idaulas+=("$i")
done < <( mysql -u "${USER}" "${DB}" \
	-N -B -e \
	"SELECT nombreaula,idaula FROM aulas ORDER BY nombreaula;" |\
	filter )

###########################################################################
#
# get computers
#

# totals computers / on
gtot=0
gton=0

i=0
while [ $i -lt ${#aulas[@]} ]
do
	echo "#### ${aulas[i]}"

	IPS=`mysql -u "${USER}" "${DB}" \
	-N -B -e \
	"SELECT ip, nombreordenador FROM ordenadores WHERE idaula=${idaulas[i]} ORDER BY nombreordenador"`

	tot=0
	ton=0

	while read -r ip nombre
	do
		DATE=`date +"%s|%H:%M:%S|%d/%m/%y"`
		R=`curl -k \
			--connect-timeout $CTIMEOUT \
			--max-time 3 \
			--silent "https://${ip}:8000/opengnsys/status"`
		tot=`expr $tot + 1`
		if [ "_$R" != "_" ]
		then
			STATUS=$(echo "$R" | jq -r '.status // "UNK"')
			LOGGED=$(echo "$R" | jq -r '.loggedin // false')
			[ "$LOGGED" == "true" ] && STATUS="${STATUS}S"
			ton=`expr $ton + 1`
		else
			STATUS=OFF
			LOGGED=false
		fi
		echo "$DATE|$nombre|$ip|$STATUS|$LOGGED"
	done < <(echo "$IPS")
	echo "## $DATE|${aulas[i]}|$ton|$tot"
	gtot=`expr $gtot + $tot`
	gton=`expr $gton + $ton`
	i=`expr $i + 1`
done

echo "## $DATE|TOTAL|$gton|$gtot"

