'''

  pyger.py
  Core script, checks on pagerduty and fires the alarms if necessary.

'''

__Author__ = 'Chris Swanson'


import alarms
import pygerduty
import ConfigParser


class Pager(object):
    '''Pagerduty class to check for paged status.'''
    def __init__(self):
        '''Initialization function'''
        # Import configs.
        self.import_conf()
        self.pager = pygerduty.PagerDuty(self.subdomain, self.apikey)

    def import_conf(self):
        '''Import Configurations for Pagerduty.'''
        configs = ConfigParser.ConfigParser()
        configs.read('config.ini')
        # Pagerdutt API Key
        self.apikey = configs.get('pagerduty', 'apikey')
        # Pagerduty subdomain
        self.subdomain = configs.get('pagerduty', 'subdomain')
        # Email of user, used for validating the alarm is for you...
        self.email = configs.get('pagerduty', 'email')
        # Heartbeat / how often to hit the pagerduty API.
        self.heartbeat = int(configs.get('pagerduty', 'heartbeat'))

    def is_paged(self):
        '''Check PagerDuty for status.'''
        pages = self.pager.incidents.list()
        for page in pages:
            email_addr = page.to_json()['assigned_to_user']['email']
            if email_addr.lower() == self.email.lower():
                alarms.run()


def main():
    '''Main function.'''
    check = Pager()
    check.is_paged()

if __name__ == '__main__':
    main()
