#!/usr/bin/python

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

import fireinfo

ENABLED_FILE = "/var/ipfire/main/send_profile"
PROXY_SETTINGS = "/var/ipfire/proxy/advanced/settings"

log_level = logging.INFO
if "-d" in sys.argv:
	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.stderr))
for handler in log.handlers:
	handler.setLevel(log_level)

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

def get_upstream_proxy():
	if not os.path.exists(PROXY_SETTINGS):
		return

	proxy_settings = {}
	with open(PROXY_SETTINGS) as f:
		for line in f.readlines():
			k, v = line.split("=", 1)
			proxy_settings[k] = v.strip()

	return {
		"host" : proxy_settings.get("UPSTREAM_PROXY", ""),
		"user" : proxy_settings.get("UPSTREAM_USER", ""),
		"pass" : proxy_settings.get("UPSTREAM_PASSWORD", ""),
	}

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

	request = urllib2.Request(PROFILE_URL % profile,
		data = urllib.urlencode({"profile" : json.dumps(profile)}),
	)
	request.add_header("User-Agent", "fireinfo/%s" % fireinfo.__version__)

	# Set upstream proxy if we have one.
	# XXX this cannot handle authentication
	proxy = get_upstream_proxy()
	if proxy["host"]:
		request.set_proxy(proxy["host"], "http")

	try:
		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():
	# Collect system information
	system = fireinfo.System()
	profile = system.profile()

	# If --dump is passed -> only dump the output.
	if "--dump" in sys.argv:
		print json.dumps(profile, sort_keys=True, indent=4)
		return 0

	if "--secret-id" in sys.argv:
		print system.secret_id
		return 0

	if "--hardware-string" in sys.argv:
		print system._unique_id
		return 0

	if not os.path.exists(ENABLED_FILE):
		del profile["profile"]

	try:
		send_profile(profile)
	except urllib2.URLError:
		return 1

	return 0

sys.exit(main())
