from datetime import datetime, timedelta

if node.has_bundle('pacman'):
    package = 'pkg_pacman:nginx'
    username = 'http'
else:
    package = 'pkg_apt:nginx'
    username = 'www-data'

directories = {
    '/etc/nginx/sites': {
        'purge': True,
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/etc/nginx/security.txt.d': {
        'purge': True,
    },
    '/etc/nginx/ssl': {
        'purge': True,
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/var/log/nginx-timing': {
        'owner': username,
        'needs': {
            package,
        },
    },
    '/var/www': {},
}

files = {
    '/etc/logrotate.d/nginx': {
        'content_type': 'mako',
        'source': 'logrotate.conf',
    },
    '/etc/nginx/nginx.conf': {
        'content_type': 'mako',
        'context': {
            'username': username,
            **node.metadata['nginx'],
        },
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/etc/nginx/fastcgi.conf': {
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/etc/nginx/sites/stub_status': {
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/etc/nginx/sites/000-port80.conf': {
        'source': 'port80.conf',
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/usr/local/share/icinga/plugins/check_nginx_status': {
        'mode': '0755',
    },
    '/var/www/error.html': {},
    '/var/www/not_found.html': {},
}
if node.has_bundle('pacman'):
    files['/etc/systemd/system/nginx.service.d/bundlewrap.conf'] = {
        'source': 'arch-override.conf',
        'triggers': {
            'action:systemd-reload',
            'svc_systemd:nginx:restart',
        },
    }

actions = {
    'nginx-generate-dhparam': {
        'command': 'openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048',
        'unless': 'test -f /etc/ssl/certs/dhparam.pem',
    },
}

svc_systemd = {
    'nginx': {
        'needs': {
            'action:nginx-generate-dhparam',
            'directory:/var/log/nginx-timing',
            package,
        },
    },
}

now = datetime.now()
in_three_months = now + timedelta(days=90)
default_security_expiry = in_three_months.strftime('%Y-%m') + '-01T00:00:00.000Z'

for vhost, config in node.metadata.get('nginx/vhosts', {}).items():
    if not 'domain' in config:
        config['domain'] = vhost

    security_txt_enabled = False
    if (
        node.metadata.get('nginx/security.txt/enabled', True) and
        config.get('security.txt', {}).get('enabled', True)
    ):
        security_txt_enabled = True

        files[f'/etc/nginx/security.txt.d/{vhost}'] = {
            'source': 'security.txt',
            'content_type': 'mako',
            'context': {
                'domain': config['domain'],
                'expiry': default_security_expiry,
                'proto': 'https' if config.get('ssl', 'letsencrypt') else 'http',
                'vhost': config.get('security.txt', node.metadata.get('nginx/security.txt', {})),
            },
        }

    files[f'/etc/nginx/sites/{vhost}'] = {
        'source': 'site_template',
        'content_type': 'mako',
        'context': {
            'create_logs': config.get('create_logs', False),
            'create_timing_log': config.get('timing_log', True),
            'php_version': node.metadata.get('php/version', ''),
            'security_txt': security_txt_enabled,
            'vhost': vhost,
            **config,
        },
        'needs': set(),
        'needed_by': {
            'svc_systemd:nginx',
            'svc_systemd:nginx:restart',
        },
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    }

    if not 'webroot' in config:
        directories[f'/var/www/{vhost}'] = config.get('webroot_config', {})

    if config.get('ssl', 'letsencrypt') == 'letsencrypt':
        files[f'/etc/nginx/sites/{vhost}']['needs'].add('action:letsencrypt_ensure-some-certificate_{}'.format(config['domain']))
        files[f'/etc/nginx/sites/{vhost}']['needed_by'].add('action:letsencrypt_update_certificates')

    elif config.get('ssl', 'letsencrypt'):
        files[f'/etc/nginx/ssl/{vhost}.crt'] = {
            'content_type': 'mako',
            'source': 'ssl_template',
            'context': {
                'domain': config['ssl'],
            },
            'needed_by': {
                'svc_systemd:nginx',
                'svc_systemd:nginx:restart',
            },
            'triggers': {
                'svc_systemd:nginx:reload',
            },
        }
        files[f'/etc/nginx/ssl/{vhost}.key'] = {
            'content': repo.vault.decrypt_file('ssl/{}.key.pem.vault'.format(config['ssl'])),
            'mode': '0600',
            'needed_by': {
                'svc_systemd:nginx',
                'svc_systemd:nginx:restart',
            },
            'triggers': {
                'svc_systemd:nginx:reload',
            },
        }

        files[f'/etc/nginx/sites/{vhost}']['needs'].add(f'file:/etc/nginx/ssl/{vhost}.crt')
        files[f'/etc/nginx/sites/{vhost}']['needs'].add(f'file:/etc/nginx/ssl/{vhost}.key')
