directories = {
    '/etc/nginx/sites': {
        'purge': True,
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    },
    '/var/www': {},
}

files = {
    '/etc/nginx/nginx.conf': {
        'content_type': 'mako',
        'context': 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',
        },
    },
    '/usr/local/share/icinga/plugins/check_nginx_status': {
        'mode': '0755',
    },
}

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',
            'pkg_apt:nginx',
        },
    },
}

if node.metadata['nginx']['use_ssl_for_all_connections']:
    # TODO rework this to support specifying a certificate instead of
    # relying on letsencrypt for the specific domain (for example to
    # support wildcard certificates
    assert node.has_bundle('letsencrypt'), 'nginx needs letsencrypt'

    files['/etc/nginx/sites/000-port80.conf'] = {
        'source': 'port80.conf',
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    }

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

    files['/etc/nginx/sites/{}'.format(vhost)] = {
        'source': 'site_template',
        'content_type': 'mako',
        'context': {
            'vhost': vhost,
            'php_version': node.metadata.get('php', {}).get('version', ''),
            **config,
        },
        'needs': set(),
        'triggers': {
            'svc_systemd:nginx:restart',
        },
    }

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

        if node.has_bundle('zfs'):
            directories['/var/www/{}'.format(vhost)]['needs'] = {
                'bundle:zfs',
            }

        directories['/var/www/{}'.format(vhost)].update(config.get('webroot_config', {}))

    if node.metadata['nginx']['use_ssl_for_all_connections']:
        files['/etc/nginx/sites/{}'.format(vhost)]['needs'].add('action:letsencrypt_update_certificates')