repo.libs.tools.require_bundle(node, 'zfs')

from os.path import join

from bundlewrap.metadata import metadata_to_json

dataset = node.metadata.get('backup-server/zfs-base')

files = {
    '/etc/backup-server/config.json': {
        'content': metadata_to_json({
            'zfs-base': dataset,
        }),
    },
    '/usr/local/bin/rotate-single-backup-client': {
        'mode': '0755',
    },
    '/usr/local/share/icinga/plugins/check_backup_for_node': {
        'mode': '0755',
    },
}

directories['/etc/backup-server/clients'] = {
    'purge': True,
}

sudoers = {}

for nodename, config in node.metadata.get('backup-server/clients', {}).items():
    sudoers[config['user']] = nodename

    users[config['user']] = {
        'home': f'/srv/backups/{nodename}',
    }

    files[f'/etc/backup-server/clients/{nodename}'] = {
        'content': metadata_to_json(config['retain']),
    }

    files[f'/srv/backups/{nodename}/.ssh/authorized_keys'] = {
        'content': repo.libs.ssh.generate_ed25519_public_key(
            config['user'],
            node,
        ),
        'owner': config['user'],
        'mode': '0400',
        'needs': {
            f'zfs_dataset:{dataset}/{nodename}',
        },
    }

    directories[f'/srv/backups/{nodename}/backups'] = {
        'owner': config['user'],
        'mode': '0700',
        'needs': {
            f'zfs_dataset:{dataset}/{nodename}',
        },
    }

files['/etc/sudoers.d/backup-server'] = {
    'source': 'sudoers',
    'content_type': 'mako',
    'context': {
        'clients': sudoers,
    },
}
