#!/usr/bin/env python

"""
StormSiren
Copyright (C) 2008  Chris Freeze <cfreeze/cfreeze_com\>

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

"""
This is StormSiren a program inspired by the StormSiren application
written by Roy McManus <slorf/users_sourceforge_net>.  Much like the
original StormSiren written by Roy McManus <slorf/users_sourceforge_net>,
this program is a simple script capable of scanning and providing
notifications of weather bulletins issued by the National
Weather Service.  StormSiren supports a wide range of paging devices
and filtering of alert types per alert device.  While inspired by
StormSiren, StormSiren is a complete rewrite that is capable of using
the new CAP/XML feeds provided at http://www.weather.gov/alerts/.

For more information there is see the README.TXT file located in the root
of this directory.
"""

import logging
import sys
import profile
from optparse import OptionParser

from StormSiren.TestAlert import TestAlert
from StormSiren.WeatherAlert import WeatherAlert
from StormSiren.StormWeather import StormWeather
from StormSiren.StormConfig import StormConfig
from StormSiren.History import History, DEFAULT_MAX_HISTORICAL_EVENTS

__RELEASE_VERSION = "2.0 RC4"
__RELEASE_MONTH   = "12"
__RELEASE_DAY     = "01"
__RELEASE_YEAR    = "2008"

logging.basicConfig(level=logging.INFO,
			format='%(asctime)s - %(name)s:%(lineno)d - %(levelname)s - %(message)s')

def main():
	parser = OptionParser()
	log = logging.getLogger()

	log.setLevel(logging.DEBUG)

	parser.add_option("-c", "--conf", dest="conf",
					help="Override configuration file", metavar="file_name", default=None)

	parser.add_option("-H", "--history", dest="history",
					help="Override file used to save history", metavar="file_name", default=None)

	parser.add_option("-m", "--maxhistory", dest="maxhistory",
					help="Override maximum history entries to maintain", metavar="integer", default=DEFAULT_MAX_HISTORICAL_EVENTS)

	parser.add_option("-s", "--simalert",
					action="store_true", dest="simalert", default=False,
					help="Simulate run and do not use alert devices")

	parser.add_option("-S", "--simfetch",
					action="store_true", dest="simfetch", default=False,
					help="Simulate the fetch using files in the examples directory")

	parser.add_option("-q", "--quiet",
					action="store_true", dest="quiet", default=False,
					help="Print only important messages to the console")

	parser.add_option("-t", "--testpage", 
					action="store_true", dest="testpage", default=False,
					help="Send a test alert to all configured devices")


	(options, args) = parser.parse_args()

	if(options.quiet):
		logging.disable(logging.debug)
		logging.disable(logging.info)

	conf = StormConfig(options.conf)

	log.info("StormSiren: v%s (%s/%s/%s)" % (__RELEASE_VERSION, 
							__RELEASE_MONTH, 
							__RELEASE_DAY, 
							__RELEASE_YEAR))
	log.info("Copyright (C) %s Chris Freeze <cfreeze\/cfreeze_com\>" % __RELEASE_YEAR)
	log.info("This is free software and comes with no warranty; see the included LICENSE file for details.")

	history_file = options.history or conf.history_file
	max_history = int(options.maxhistory) or conf.max_history
	history = History(history_file, max_history)

	#conf.display()
	#history.display()

	if(len(conf.devices) == 0):
		log.error("No valid devices found, exiting..")
		sys.exit(1)

	if(not options.testpage):
		for state in conf.states:
			log.info("State: " + state)
			xw = StormWeather(state,history,options.simfetch,options.simalert,conf.proxy)
			#xw.display()
			for dev in conf.devices:
				if(dev.isStateWanted(state)):
					xw.registerDevice(dev)
			xw.fetch()

		history.save()
	else:
		log.info("Sending test page to all devices")
		ta = TestAlert("examples/test-alert.cap")
		ta.fetch()
		for dev in conf.devices:
			log.info("\tSending test alert to:\n%s" % dev.__str__())
			dev.send(ta.weather_alert)


if __name__ == "__main__":
	#profile.run("main()","siren.stats")
	main()

