#!/usr/bin/env python3
import subprocess
import os
import argparse
import time

def get_arguments():
    parser = argparse.ArgumentParser()

    # argument groups can have their tickers combined (ie -su)
    bools = parser.add_argument_group()

    # REQUIRED string value
    parser.add_argument('-f', '--full_filepath', help='Full filepath to the nginx conf file. Example: /etc/nginx/conf.d/example.conf', required=True)

    # REQUIRED string value
    parser.add_argument('-d', '--comma_separated_domains', help='Comma separated domains means no spaces are allowed. Example: example.com,www.example.com', required=True)

    # # integer value
    # parser.add_argument('-m', '--max', default=136, type=int,
    #                     help='')

    bools.add_argument('-s', dest='staging', action='store_true',
                       help='Is this a staging configuration file? Staging has different location for the static files and operates on a different port')

    # # boolean (default=True; store_false means if ticked then args['sexy'] == False)
    # bools.add_argument('-s', dest='sexy', action='store_false',
    #                    help='are you sexy')

    args = parser.parse_args()

    return args


if __name__ == '__main__':
    args = get_arguments()
    print(args)

    print('\n\n-------\n')
    print('This will update your nginx conf file with the default basic settings applicable to gunicorn with static files served by nginx.')
    print('\n-------\n')

    port = 5001 if args.staging else 5000
    static_file_directory = '/var/www-staging/html' if args.staging else '/var/www/html'

    time.sleep(1)

    domains = ' '.join(args.comma_separated_domains.split(','))

    redirect_block_func = lambda domain: f'''
    if ($host = {domain}) {{
        return 301 https://$host$request_uri;
    }} # managed by Certbot
    '''

    redirect_block = '\n'.join([redirect_block_func(domain) for domain in domains.split(' ')])

    for domain in domains.split(' '):
        if len(domain.split('.')) == 2:
            base_domain = domain


    if 'base_domain' not in locals():
        print('Error: Could not find base domain. Please input the primary domain (e.g. example.com). Exiting.')
        exit(1)

    conf_text = f'''
server {{
    server_name {domains};

    listen [::]:443 ssl http2 ipv6only=on; # managed by Certbot
    listen 443 ssl http2; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/{base_domain}/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/{base_domain}/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    location /static/ {{
        autoindex on;
        root {static_file_directory};
        expires 7d;
        access_log off;
        add_header Cache-Control "public";
    }}

    location / {{
        proxy_set_header X-Forwarded-Host $host:$server_port;
        proxy_set_header X-Forwarded-Server $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_pass      http://127.0.0.1:{port};
    }}

}}
server {{
    {redirect_block}
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name {domains};
    return 404; # managed by Certbot

}}
'''

    with open(args.full_filepath, 'w') as f:
        f.write(conf_text)

    print('\n\n-------')
    print('Success!')
    print('-------')