#!/usr/bin/env python
from __future__ import print_function

import sys
PY3 = sys.version_info.major >= 3
import time
import argparse
if PY3:
    from http.server import BaseHTTPRequestHandler, HTTPServer
else:
    from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer


from socket import AF_INET6


class WebHello(BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200) # ok
        self.send_header("Content-type", "text/plain")
        self.end_headers()

        msg = "My first HELLLOOO %s at `%s`  ; %s  (python %s)" % (
                ' '.join(self.server.webhello_argv) or 'world',
                self.path, time.asctime(), sys.version.replace('\n', ' '))
        if PY3:
            msg = msg.encode()
        self.wfile.write(msg)


class HTTPServerV6(HTTPServer):
    address_family = AF_INET6

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--logfile', dest='logfile')
    parser.add_argument('--bind_ip', help='bind_ip', required=True)
    parser.add_argument('--bind_port', help='port', type=int, required=True)
    parser.add_argument('--name', help='name', required=True)

    args = parser.parse_args()
    bind_ip = args.bind_ip
    bind_port = args.bind_port
    name = args.name

    # HTTPServer logs to sys.stderr - override it if we have --logfile
    if args.logfile:
        f = open(args.logfile, 'a', buffering=1)
        sys.stderr = f

    print('* %s helloweb.py starting at %s' % (
        time.asctime(), (bind_ip, bind_port)), file=sys.stderr)

    # TODO autodetect ipv6/ipv4
    httpd = HTTPServerV6( (bind_ip, bind_port), WebHello)
    httpd.webhello_argv = name
    httpd.serve_forever()

if __name__ == '__main__':
    main()
