#!/usr/bin/python

import json
import logging
import logging.handlers
import sys
import urllib
import urllib2

import fireinfo

log_level = logging.DEBUG

# Setup logging
log = logging.getLogger()
log.setLevel(log_level)
log.addHandler(logging.handlers.SysLogHandler("/dev/log"))
log.addHandler(logging.StreamHandler(sys.stdout))
for handler in log.handlers:
	handler.setLevel(log_level)

PROFILE_URL = "http://stasy.ipfire.org/send/%(public_id)s"

def send_profile(profile):
	logging.debug("Sending profile:")
	for line in json.dumps(profile, sort_keys=True, indent=4).splitlines():
		logging.debug(line)

	try:
		request = urllib2.Request(PROFILE_URL % profile,
			data = urllib.urlencode({"profile" : json.dumps(profile)}),
		)
		urllib2.urlopen(request, timeout=60)
	except (urllib2.HTTPError, urllib2.URLError), e:
		reason = "Unknown reason"

		if isinstance(e, urllib2.HTTPError):
			reason = "%s" % e
		elif isinstance(e, urllib2.URLError):
			reason = e.reason

		logging.error("Profile was not sent propertly: %s" % reason)
		return

	logging.debug("Profile was sent successfully.")

def main():
	logging.info("%s was started." % sys.argv[0])

	# Collect system information
	system = fireinfo.System()
	try:
		send_profile(system.profile())
	except urllib2.URLError:
		return 1

	return 0

sys.exit(main())
