from django.core.management.base import BaseCommand
from django.core.management.base import CommandError
from django.conf import settings
from os.path import abspath
from optparse import make_option
import socket
import re

class Command(BaseCommand):
    args = '<domain> [<domain>]'
    option_list = BaseCommand.option_list + (
        make_option(
            '--port',
            action='store',
            dest='tcp_port',
            default=8099,
            help='The tcp port to use for Nginx to talk to Django.'
            ),
        make_option(
            "--host-address",
            action="store",
            default="_",
            dest="host_address",
            help="The ip address for nginx to listen on, use _ to try to resolve the domain name (the default)"
            )
        )

    help = 'Generates an Nginx config to map the current Django app to Nginx.'

    def handle(self, *args, **options):
        domain = args[0]
        domains = ""
        if len(args) > 1:
            domains = args[1:]

        host_addr = options["host_address"]
        if host_addr == "_":
            host_addr = socket.gethostbyname(domain)
        elif not re.match("^([0-9]+\\.){3}[0-9]+$", host_addr):
            host_addr = socket.gethostbyname(host_addr)

        variables = {
            "HOST_ADDRESS": host_addr,
            "PORT": options["tcp_port"],
            "DOMAIN": domain,
            "DOMAINS": " ".join(domains),
            "UPSTREAM_NAME": "django__" + domain.replace(".", "__"),
            "STATIC_URL": settings.STATIC_URL,
            "DOCROOT": abspath(settings.STATIC_ROOT),
            }
        config = """# Nginx config generated by django-config

upstream %(UPSTREAM_NAME)s {
   server localhost:%(PORT)s;
}

server {
listen  %(HOST_ADDRESS)s:80;
server_name %(DOMAIN)s %(DOMAINS)s;
root %(DOCROOT)s;

location %(STATIC_URL)s {
   rewrite ^%(STATIC_URL)s(.*)$ /$1 break;
}

location  / {
   proxy_pass http://%(UPSTREAM_NAME)s;
   proxy_redirect off;
   proxy_set_header Host "%(DOMAIN)s";
   proxy_next_upstream error timeout;
   proxy_connect_timeout 120;
   proxy_send_timeout 120;
   proxy_read_timeout 120;
}

}
""" % variables
        print config

# End



