#!/usr/bin/python2.7
import socket
import errno
import cgi
import os
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class MyHandler(BaseHTTPRequestHandler):

  def do_GET(self):
    if self.path == '/ip':
      self.send_response(200)
      self.send_header('Content-type', 'text/html')
      self.end_headers()
      self.wfile.write('Your IP address is %s' % self.client_address[0]) 
      return    
    else:
      return SimpleHTTPRequestHandler.do_GET(self)

  def do_POST(self):     
    form = cgi.FieldStorage(
      fp=self.rfile,
      headers=self.headers,
      environ={"REQUEST_METHOD": "POST"}
    )

    lw.write_log(form.list[0].value, form.list[1:])
    self.send_response(200)

class HTTPServerV6(HTTPServer):
  address_family = socket.AF_INET6

class logWriter():
  def write_log(self, fp, contents):
    print os.path.dirname(fp)
    try:
      os.makedirs(os.path.dirname(fp))
    except OSError as exception:
      if exception.errno != errno.EEXIST:
        raise
    try:
      with open(fp, 'a') as myfile:
        for l in contents:
          myfile.write(l.value)
    except IOError as e:
      print "Unable to open file" #Does not exist OR no read permissions
      with open(fp, 'w') as myfile:
        for l in contents:
          myfile.write(l.value)
    print "Finished writing"

if __name__ == '__main__':  
  lw = logWriter()
  server = HTTPServerV6(('::', 9000), MyHandler)
  print 'Starting server, use <Ctrl-C> to stop'
  server.serve_forever()
