from bundlewrap.metadata import atomic

defaults = {
    'apt': {
        'packages': {
            'jellyfin': {},
        },
        'repos': {
            'jellyfin': {
                'uris': {
                    'https://repo.jellyfin.org/{os}'
                },
            },
        },
    },
    'backups': {
        'paths': {
            f'/var/lib/jellyfin/{x}' for x in ('data', 'metadata', 'plugins', 'root')
        },
    },
    'icinga2_api': {
        'transmission': {
            'services': {
                'JELLYFIN PROCESS': {
                    'command_on_monitored_host': '/usr/lib/nagios/plugins/check_procs -C jellyfin -c 1:',
                },
            },
        },
    },
}


@metadata_reactor.provides(
    'nginx/vhosts/jellyfin',
)
def nginx(metadata):
    if not node.has_bundle('nginx'):
        raise DoNotRunAgain

    if 'jellyfin' not in metadata.get('nginx/vhosts', {}):
        return {}

    return {
        'nginx': {
            'vhosts': {
                'jellyfin': {
                    'do_not_add_content_security_headers': True,
                    'locations': {
                        '/': {
                            'target': 'http://127.0.0.1:8096',
                            'websockets': True,
                        },
                    },
                },
            },
        },
    }

@metadata_reactor.provides(
    'firewall/port_rules',
)
def firewall(metadata):
    return {
        'firewall': {
            'port_rules': {
                '8096/tcp': atomic(metadata.get('jellyfin/restrict-to', {'*'})),
            },
        },
    }