#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""Automatic Docker Deployment via Webhooks"""

from os import system
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from BaseHTTPServer import BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer as HTTPServer
from SocketServer import ThreadingMixIn
import sys
import threading
    

class RequestHandler(BaseHTTPRequestHandler):
    """A POST request handler which expects a token in its path."""
    def do_POST(self):
        image, token = self.path[1:].split("/")
        if args.token == token and image:
            cmd = " ".join(args.cmd)
            print "Running: %s %s" % (cmd, image)
            system("%s %s" % (cmd, image))
            self.send_response(200, "OK")
        else:
            self.send_response(401, "Not authorized")
        self.end_headers()


def get_parser():
    """Get a command line parser for docker-hook."""
    parser = ArgumentParser(description=__doc__,
                            formatter_class=ArgumentDefaultsHelpFormatter)

    parser.add_argument("-t", "--token",
                        dest="token",
                        required=True,
                        help=("Secure auth token (can be choosen "
                              "arbitrarily)"))
    parser.add_argument("-c", "--cmd",
                        dest="cmd",
                        required=True,
                        nargs="*",
                        help="Command to execute when triggered")
    parser.add_argument("--addr",
                        dest="addr",
                        default="0.0.0.0",
                        help="address where it listens")
    parser.add_argument("--port",
                        dest="port",
                        type=int,
                        default=8555,
                        metavar="PORT",
                        help="port where it listens")
    return parser


class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""


def main(addr, port):
    """Start a HTTPServer which waits for requests."""
    httpd = ThreadedHTTPServer((addr, port), RequestHandler)
    print "Running on", addr, port
    httpd.serve_forever()

if __name__ == '__main__':
    parser = get_parser()
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    args = parser.parse_args()
    main(args.addr, args.port)
