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):
    # make sure nobody tries to do something funny
    for file in {
        '/etc/backup.priv',
        '/usr/local/bin/generate-backup',
        '/usr/local/bin/generate-backup-with-retries',
        '/var/tmp/backup.monitoring', # status file
    }:
        files[file] = {
            'delete': True,
        }

else:
    backup_target = repo.get_node(node.metadata.get('backup-client/target'))

    files['/etc/backup.priv'] = {
        'content': repo.libs.ssh.generate_ed25519_private_key(
            node.metadata.get('backup-client/user-name'),
            backup_target,
        ),
        'mode': '0400',
    }

    files['/usr/local/bin/generate-backup'] = {
        'content_type': 'mako',
        'context': {
            'username': node.metadata.get('backup-client/user-name'),
            'server': backup_target.metadata.get('backup-server/my_hostname'),
            'port': backup_target.metadata.get('backup-server/my_ssh_port'),
            'paths': backup_paths,
        },
        'mode': '0700',
    }

    files['/usr/local/bin/generate-backup-with-retries'] = {
        'mode': '0700',
    }

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

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

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

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',
    }
