from os.path import join

if node.has_bundle('zfs'):
    wanted_paths = node.metadata.get('backups/paths', set())
    snapshot_paths = node.metadata.get('zfs/filesystems_with_backup_snapshots', {})
    backup_paths = set()

    for path in wanted_paths:
        path_found = False
        for zfs_paths in snapshot_paths.values():
            if path in zfs_paths:
                backup_paths.add(f'/mnt/backup-snapshot{path}')
                path_found = True

        if not path_found:
            backup_paths.add(path)
else:
    backup_paths = node.metadata.get('backups/paths', set())

if node.metadata.get('backups/exclude_from_backups', False):
    files['/etc/backup.priv'] = {
        'delete': True,
    }
else:
    if ':' in node.metadata['backup-client']['server']:
        server, port = node.metadata['backup-client']['server'].split(':')
    else:
        server = node.metadata['backup-client']['server']
        port = 22

    files['/usr/local/bin/generate-backup'] = {
        'content_type': 'mako',
        'context': {
            'username': node.metadata['backup-client']['user-name'],
            'server': server,
            'port': port,
            'paths': backup_paths,
        },
        'mode': '0700',
    }
    files['/etc/backup.priv'] = {
        'content': repo.vault.decrypt_file(join('backup', 'keys', f'{node.name}.key.vault')),
        'mode': '0400',
    }

files['/usr/local/share/icinga/plugins/check_backup_last_run'] = {
    'mode': '0755',
}

files['/etc/logrotate.d/backup-client'] = {
    'source': 'logrotate.conf',
}

directories['/etc/backup-pre-hooks.d'] = {
    'purge': True,
}

directories['/var/log/backup-client'] = {}

for hname, hcontent in node.metadata.get('backup-client/pre-hooks', {}).items():
    files[f'/etc/backup-pre-hooks.d/50-{hname}'] = {
        'content': '#!/bin/sh\n\n' + hcontent,
        'mode': '0700',
    }