#!/bin/sh
echo 0 > /tmp/room_event_active
while true
do
echo "select * from flex_room_setting_mode_events" | PGPASSWORD=nosahp psql -t --host=localhost -d omniselect -U phasonapps |
 uniq > /tmp/room_events_table

override_status=`cat /tmp/room_events_table | awk 'BEGIN{status=0;FS="|"}END{print status}$5==1{status=1}'`
if test -e /media/pi/PHASON/DEBUG1
then
        debug_mode=1
else
        debug_mode=0
fi

date=`date "+%Y-%m-%d %H-%M-%S"`
active_event=`cat /tmp/room_event_active`
cat /tmp/room_events_table |
awk -v debug_mode=$debug_mode -v date="$date" -v active_di="$active_event" -v override_status=$override_status '
BEGIN {
FS = "|"
split(date, sa, " ")
   split(sa[1], sd,"-")
   split(sa[2], st,"-")
}

{
        rec_id = $1
        room_id = $2
        setting_num = $3
        split($4, a, " ")
           split(a[1],d,"-")
           split(a[2],t,":")
        temp_t = $5
        user = $6
        if(temp_t == 0) {
                        trec = (d[1] - 1970) * 31540000 + d[2] * 2628000 + d[3] * 86400 + t[1] * 3600 + t[2] * 60 + t[3]
                tact = (2000 - 1970) * 31540000 + sd[2] * 2628000 + sd[3] * 86400 + st[1] * 3600 + st[2] * 60 + st[3]

                if(trec > (tact - 450) && trec < (tact + 450)) {
                        cmd = sprintf("curl -s -d \"room_id=%i&settingGroup=%i&user=%s\" -X POST http://localhost/afx/afx_php/updateRoomSettingNum.php > /tmp/room_events.log", room_id, setting_num, user)
                        if(debug_mode == 1){
                        print "DEBUG: " date " " cmd
                        }

                        system(cmd)
                        cmd = sprintf("echo %i > /tmp/room_event_active \n", rec_id)
                        system(cmd)
                }
        }
        if(temp_t == 1) {
                trec = (d[1] - 1970) * 31540000 + d[2] * 2628000 + d[3] * 86400 + t[1] * 3600 + t[2] * 60 + t[3]
                tact = (sd[1] - 1970) * 31540000 + sd[2] * 2628000 + sd[3] * 86400 + st[1] * 3600 + st[2] * 60 + st[3]
                if(trec < tact) {
                print date " +++++ " $4
                        cmd = sprintf("curl -s -d \"room_id=%i&settingGroup=%i&user=%s\" -X POST http://localhost/afx/afx_php/updateRoomSettingNum.php > /tmp/room_events.log", room_id, setting_num, user)
                        if(debug_mode == 1) {
                        print "DEBUG: " date " " cmd
                        }
                        system(cmd)
                        cmd = sprintf("echo \"delete from flex_room_setting_mode_events where room_setting_mode_event_id=%i\" | PGPASSWORD=nosahp psql -t --host=localhost -d omniselect -U phasonapps > /tmp/room_events.log", rec_id)
                        if(debug_mode = 1) {
                        print "DEBUG: " date " " cmd
                        }
                        system(cmd)
                }
        }
}'

sleep 120
done
