#!/usr/local/bin/bash

DB=/var/db/univnautes-sp.sqlite3
SPDIR=/usr/local/univnautes/sp

cd $SPDIR

function cronstop() {
    for cron in update-metadatas update-geoinfos update-whitelists clearsessions-pf
    do
        if [ -r /var/run/${cron}-cron.pid ]
            then
                PID=`cat /var/run/${cron}-cron.pid`
                ps waux | grep "$PID" | grep minicron | grep -vq grep && kill $PID
                rm -f /var/run/${cron}-cron.pid
            fi
    done
}
function cronstart() {
    cronstop
    /usr/local/bin/minicron 3600 /var/run/update-metadatas-cron.pid $SPDIR/update-metadatas.sh
    /usr/local/bin/minicron 3600 /var/run/update-geoinfos-cron.pid $SPDIR/update-geoinfos.sh
    /usr/local/bin/minicron 3600 /var/run/update-whitelists-cron.pid $SPDIR/update-whitelists.sh
    /usr/local/bin/minicron 600 /var/run/clearsessions-pf-cron.pid $SPDIR/clearsessions-pf.sh
}

function syncwl() {
    echo "sync whitelists in progress (backgrounded)" | logger -p local4.info -t sp/syncwhitelists
    (
      cd /usr/local/univnautes/sp/
      ./update-whitelists.sh | logger -p local4.info -t sp/update-whitelists
    ) &
}

function syncbl() {
    echo "sync blacklist in progress (backgrounded)" | logger -p local4.info -t sp/syncblacklists
    (
      cd /usr/local/univnautes/sp/
      ./update-blacklists.sh | logger -p local4.info -t sp/update-blacklists
    ) &
}

function syncdata() {
    echo "sync metadatas + geoinfos in progress (backgrounded)" | logger -p local4.info -t sp/syncdata
    (
      cd /usr/local/univnautes/sp/
      ./update-metadatas.sh | logger -p local4.info -t sp/update-metadatas
      ./update-geoinfos.sh | logger -p local4.info -t sp/update-geoinfos
    ) &
}

function syncdb() {
    if ! test -r $DB
    then
        python manage.py syncdb --noinput --no-initial-data | logger -p local4.info -t sp/syncdb
        python manage.py loaddata fixtures/* | logger -p local4.info -t sp/loaddata
    fi
}

function start() {
    syncdb
    python manage.py collectstatic -v0 -l --noinput | logger -p local4.info -t sp/collectstatic
    python manage.py runfcgi socket=/tmp/univnautes-sp-fcgi.sock method=prefork daemonize=true pidfile=/var/run/univnautes-sp-fcgi.pid
    echo "started (manage.py runfcgi)" | logger -p local4.info -t sp/start
    syncdata
    syncwl
    syncbl
    cronstart
}

function stop() {
    cronstop
    kill $(cat /var/run/univnautes-sp-fcgi.pid)
    echo "stopped (kill)" | logger -p local4.info -t sp/stop
}

function restart() {
    stop
    sleep 1
    start
}

function status() {
    ps waux | grep $(cat /var/run/univnautes-sp-fcgi.pid) |  grep -v grep
}

echo $1 | logger -p local4.info -t sp/rc

$1

