#!/usr/bin/python

# Copyright (C) 2009 Jean-Baptiste LAMY
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


DEVICE_STARTUP_TIME = 10 # in seconds
SUNBIRD_DB          = "/home/jiba/.mozilla/sunbird/4tj4rt58.default/storage.sdb"

import time
from pysqlite2 import dbapi2 as sqlite

con = sqlite.connect(SUNBIRD_DB)
cur = con.cursor()

cur.execute("select event_start, alarm_offset from cal_events")

alarms = [start / 1000000 + offset for start, offset in cur.fetchall() if offset != None]
print alarms

now = int(time.time())
next_alarm = 9999999999
for alarm in alarms:
  if (alarm > now) and (alarm < next_alarm):
    next_alarm = alarm
    
if next_alarm != 9999999999:
  next_alarm -= DEVICE_STARTUP_TIME
  print next_alarm
  open("/sys/class/rtc/rtc0/wakealarm", "w").write("0")
  open("/sys/class/rtc/rtc0/wakealarm", "w").write(str(next_alarm))

