#!/usr/bin/env python
################################################################################
# Name:
#   cbu-updater-service
# Description:
#   Periodically launches an updater check for cloud backup. Typically this is
#   once per 24 hours. If a SIGINT is received, it stops. If a SIGUSR1/SIGUSR2
#   is received, it immediately runs updater/agent out-of-date check, instead of
#   waiting for the full 24 hours.
# Requires parameters:
#   N/A
# Requires environment variables:
#   N/A

import os
import sys
import signal
import time
import datetime

################################################################################
# Capture and flag signals sent to this service.                               # 
################################################################################
class SignalHandler():
  def __init__(self):
    self.ClearAll()

  def ClearAll(self):
    self.SIGINT = False
    self.SIGUSER1 = False
    self.SIGUSER2 = False

  def SignalHandlerSIGINT(self, signal, frame):
    self.SIGINT = True

  def SignalHandlerSIGUSER1(self, signal, frame):
    self.SIGUSER1 = True

  def SignalHandlerSIGUSER2(self, signal, frame):
    self.SIGUSER2 = True

handler = SignalHandler()
signal.signal(signal.SIGINT, handler.SignalHandlerSIGINT)
signal.signal(signal.SIGUSR1, handler.SignalHandlerSIGUSER1)
signal.signal(signal.SIGUSR2, handler.SignalHandlerSIGUSER2)

################################################################################
# Call the updater script every 24 hours.                                      # 
################################################################################
while (not handler.SIGINT):
  # TODO: ROLL THIS LOG PERIODICALLY
  # TODO: DATE-TAG EVERY TIME THIS WHILE-LOOP TRIGGERS
  os.system('/usr/bin/cloudbackup-updater >>/var/log/cbu-updater-stdout.log 2>&1')
  targetdate = datetime.datetime.now() + datetime.timedelta(hours=24)
  handler.ClearAll()
  while True:
    time.sleep(1)
    if handler.SIGINT:
      sys.exit(0)
    if handler.SIGUSER1:
      break
    if handler.SIGUSER2:
      break
    if (targetdate > datetime.datetime.now()):
      continue

