import os
from subprocess import call

NGINX_CONF_ROOT = "/etc/nginx/conf.d/"
NGINX_CONF_TEMPLATE = """
server {
    listen       80;
    server_name  %s;

    location / {
        proxy_pass http://127.0.0.1:%d;
    }
}
"""


def create_proxy(domain, subdomain, port):
    """ Create nginx proxy_pass for the given domain on given port
    :param string domain: domain of item, e.g. blastedstudios.com
    :param string subdomain: desired subdomain of item, e.g. test1
    :param string port: port of server for proxy (generated by ssh remote forward)
    """
    server_name = subdomain + "." + domain
    nginx_conf_text = NGINX_CONF_TEMPLATE % (server_name, port)
    nginx_conf_path = proxy_conf_path(subdomain)
    # assume we have permissions - percolate exception otherwise
    with open(nginx_conf_path, "w") as conf:
        conf.write(nginx_conf_text)
    # after writing new conf, we need to reload nginx
    call(["nginx", "-s", "reload"])


def delete_proxy(domain, subdomain, port):
    """ Remove previously created proxy for domain on port """
    nginx_conf_path = proxy_conf_path(subdomain)
    os.remove(nginx_conf_path)
    call(["nginx", "-s", "reload"])


def proxy_conf_path(subdomain):
    """ Get path for given subdomain """
    return os.path.join(NGINX_CONF_ROOT, subdomain + ".conf")
