#!/bin/sh

# lock to avoid concurrent updates
LOCK=/var/run/univnautes-update-map_in-progress.lock
if [ -r $LOCK ]
then
	PID=`cat $LOCK`
	ps waux | grep $PID | grep univnautes | grep -vq grep && exit
fi
unlock() {
	rm -f $LOCK
	exit
}
trap unlock INT TERM EXIT
echo $$ > $LOCK

# config
. /usr/local/univnautes/etc/univnautes.conf

log() {
	logger -p local4.info -t update-map -- "$*"
}

log "build login.html with geo locations"

GEOURLS=/var/lib/univnautes/geourls
GEOLOCAL=/var/lib/univnautes/geolocal
LOGINHTML=/var/lib/univnautes/templates/login.html

GEODIR=/var/lib/univnautes/geofiles
mkdir -p $GEODIR
GEOFILES=""

# build urls list from file
GEOURLS=`cat $GEOURLS 2> /dev/null | tr -d 
 | xargs`
# if file is empty, use default urls (renater federation)
if [ -z "$GEOURLS" ]
then
	GEOURLS="https://static.discojuice.org/feeds/renater http://isos.univnautes.entrouvert.com/univnautes.geo"
fi

n=1
for url in $GEOURLS
do
	GEOFILE=$GEODIR/$n
	wget -q --no-check-certificate -O $GEOFILE $url
	if [ $? -eq 0 ]
	then
		log "$url OK ($n)"
		GEOFILES=$GEOFILES" "$GEOFILE
		n=$(($n+1))
	else
		log "cannot download $url"
	fi
done

if [ -r $GEOLOCAL ]
then
	GEOFILES=$GEOFILES" "$GEOLOCAL
	log "use local geo locations ($n)"
fi

# virtualenv activation 
VIRTUAL_ENV="/usr/local/univnautes"
export VIRTUAL_ENV
PATH="$VIRTUAL_ENV/bin:$PATH"
export PATH

# create indexhtml
cd /usr/local/univnautes/pffedportal
if [ -r pffedportal.db ]
then
	python ./create_loginhtml.py $GEOFILES 2>&1 > $LOGINHTML | logger -p local4.info -t update-map
	log "login.html created"
else
	log "pffedportal.db is not ready"
fi

exit 0
