#!/usr/bin/env python

# Sends an error report (if the report-error class was enabled) to a remote server.
#
# Copyright (C) 2013 Intel Corporation
# Author: Andreea Proca <andreea.b.proca@intel.com>



import httplib, urllib, os, sys, json, base64
from urllib2 import _parse_proxy as parseproxy


def handle_connection(server, data):
    params = urllib.urlencode({'data': data})
    headers = {"Content-type": "application/json"}
    proxyrequired = False
    if os.environ.get("http_proxy") or os.environ.get("HTTP_PROXY"):
        proxyrequired = True
        # we need to check that the server isn't a local one, as in no_proxy
        try:
            temp = httplib.HTTPConnection(server, strict=True, timeout=5)
            temp.request("GET", "/Errors/")
            tempres = temp.getresponse()
            if tempres.status == 200:
                proxyrequired = False
            temp.close()
        except:
            pass

    if proxyrequired:
        proxy = parseproxy(os.environ.get("http_proxy") or os.environ.get("HTTP_PROXY"))
        if proxy[1] and proxy[2]:
            auth = base64.encodestring("%s:%s" % (proxy[1], proxy[2]))
            headers["Authorization"] = "Basic %s" % auth
        conn = httplib.HTTPConnection(proxy[3])
        conn.request("POST", "http://%s/ClientPost/" % server, params, headers)
    else:
        conn = httplib.HTTPConnection(server)
        conn.request("POST", "/ClientPost/", params, headers)

    return conn


def sendData(json_file, server):

    if os.path.isfile(json_file):

        home = os.path.expanduser("~")
        userfile = os.path.join(home, ".oe-send-error")
        if os.path.isfile(userfile):
            with open(userfile) as g:
                username = g.readline()
                email = g.readline()
        else:
            print("Please enter your name and your email (optionally), they'll be saved in the file you send.")
            username = raw_input("Name: ")
            email = raw_input("E-mail (not required): ")
            if len(username) > 0 and len(username) < 50:
                with open(userfile, "w") as g:
                    g.write(username + "\n")
                    g.write(email + "\n")
            else:
                print("Invalid inputs, try again.")
                return

        with open(json_file) as f:
            data = f.read()

        try:
            jsondata = json.loads(data)
            jsondata['username'] = username.strip()
            jsondata['email'] = email.strip()
            data = json.dumps(jsondata, indent=4, sort_keys=True)
        except:
            print("Invalid json data")
            return

        try:
            conn = handle_connection(server, data)
            response = conn.getresponse()
            print response.status, response.reason
            res = response.read()
            if response.status == 200:
                print(res)
            else:
                print("There was a problem submiting your data, response written in %s.response.html" % json_file)
                with open("%s.response.html" % json_file, "w") as f:
                    f.write(res)
            conn.close()
        except Exception as e:
                print("Server connection failed: %s" % e)

    else:
        print("No data file found.")


if __name__ == '__main__':
    print ("\nSends an error report (if the report-error class was enabled) to a remote server.")
    print("\nThis scripts sends the contents of the error to a public upstream server.")
    print("\nPlease remove any identifying information before sending.")
    if len(sys.argv) < 2:
        print("\nUsage: send-error-report <error_fileName> [server]")
        print("\nIf this is the first when sending a report you'll be asked for your name and optionally your email address.")
        print("They will be associated with your report.\n")

    elif len(sys.argv) == 3:
        sendData(sys.argv[1], sys.argv[2])
    else:
        sendData(sys.argv[1], "errors.yoctoproject.org")
