#!/usr/bin/bash

d=$(date -Iminutes)

cd /home/qeebmisk

set +e
/usr/bin/python3.6 scraper.py >new_meta 2> "scraper_$d.log"
result=$?
if [ $result -eq 0 ]
then
    /usr/bin/sqlite3 timetable.db 'pragma integrity_check;'
    if [ $? -eq 0 ]
    then
        trap except ERR

        echo 'making metadata' >> "scraper_$d.log"
        mv new_meta timetable.db.meta
        sha512sum timetable.db | cut -d ' ' -f 1 >>timetable.db.meta
        ls -l timetable.db | cut -d ' ' -f 5 >>timetable.db.meta
        echo '1.1.0' >>timetable.db.meta
        echo 'timetable.db.xz' >>timetable.db.meta
        
        xz -z -k timetable.db

        echo 'moving' >> "scraper_$d.log"
        mv timetable.db.xz public_html/w/data/media/programmes/bimba/timetable.db.xz
        mv timetable.db.meta public_html/w/data/media/programmes/bimba/timetable.db.meta

        echo 'success' >> "scraper_$d.log"
    else
        echo 'db integrity check failed' >> "scraper_$d.log"
        rm timetable.db
        rm new_meta
    fi
elif [ $result -eq 48 ]
then
    echo 'db is still valid' >> "scraper_$d.log"
    rm new_meta
else
    echo 'scraper failed' >> "scraper_$d.log"
    rm timetable.db
    rm new_meta
fi

function except {
    (rm /home/qeebmisk/timetable.db; rm /home/qeebmisk/new_meta) || :
}
