from bundlewrap.exceptions import BundleError

supported_os = {
    'debian': {
        10: 'buster',
        11: 'bullseye',
        12: 'bookworm',
        99: 'unstable',
    },
    'raspbian': {
        10: 'buster',
    },
}

try:
    supported_os[node.os][node.os_version[0]]
except (KeyError, IndexError):
    raise BundleError(f'{node.name}: OS {node.os} {node.os_version} is not supported by bundle:apt')


actions = {
    'apt_update': {
        'command': 'apt-get update',
        'needed_by': {
            'pkg_apt:',
        },
        'triggered': True,
        'cascade_skip': False,
    },
}

files = {
    '/etc/apt/sources.list': {
        'source': 'sources.list-{}-{}'.format(node.os, supported_os[node.os][node.os_version[0]]),
        'triggers': {
            'action:apt_update',
        },
    },
    '/etc/cloud': {
        'delete': True,
    },
    '/etc/kernel/postinst.d/unattended-upgrades': {
        'source': 'kernel-postinst.d',
        'mode': '0755',
    },
    '/etc/netplan': {
        'delete': True,
    },
    '/etc/upgrade-and-reboot.conf': {
        'content_type': 'mako',
    },
    '/usr/local/sbin/upgrade-and-reboot': {
        'mode': '0700',
    },
    '/usr/local/sbin/do-unattended-upgrades': {
        'content_type': 'mako',
        'mode': '0700',
        'context': {
            'additional_update_commands': node.metadata.get('apt/additional_update_commands', set()),
            'clean_old_kernels': node.metadata.get('apt/clean_old_kernels', True),
            'restart_triggers': node.metadata.get('apt/restart_triggers', {}),
        }
    },
    '/usr/local/share/icinga/plugins/check_unattended_upgrades': {
        'mode': '0755',
    },
    '/var/lib/cloud': {
        'delete': True,
    },
}

directories = {
    '/etc/apt/sources.list.d': {
        'purge': True,
        'triggers': {
            'action:apt_update',
        },
    },
}

svc_systemd = {
    'apt-daily.timer': {
        'running': False,
        'enabled': False,
    },
    'apt-daily-upgrade.timer': {
        'running': False,
        'enabled': False,
    },
}

pkg_apt = {
    'apt-transport-https': {},

    'arping': {},
    'at': {},
    'build-essential': {},
    'bzip2': {},
    'curl': {},
    'diffutils': {},
    'dnsutils': {},
    'git': {},
    'grep': {},
    'gzip': {},
    'htop': {},
    'jq': {},
    'less': {},
    'logrotate': {},
    'lsof': {},
    'mailutils': {},
    'manpages': {},
    'moreutils': {},
    'mount': {},
    'mtr': {},
    'ncdu': {},
    'ncurses-term': {},
    'netcat-openbsd': {},
    'nmap': {},
    'python3': {},
    'python3-dev': {},
    'python3-setuptools': {
        'needed_by': {
            'pkg_pip:',
        },
    },
    'python3-pip': {
        'needed_by': {
            'pkg_pip:',
        },
    },
    'python3-virtualenv': {},
    'rsync': {},
    'tar': {},
    'tcpdump': {},
    'telnet': {},
    'tmux': {},
    'tree': {},
    'unzip': {},
    'vim': {},
    'wget': {},
    'whois': {},
    'zip': {},

    'cloud-init': {
        'installed': False,
    },
    'molly-guard': {
        'installed': False,
    },
    'netplan.io': {
        'installed': False,
    },
    'popularity-contest': {
        'installed': False,
    },
    'python3-packaging': {
        'installed': False,
    },
    'unattended-upgrades': {
        'installed': False,
    },
}

if node.os_version[0] >= 11:
    symlinks = {
        '/usr/bin/python': {
            'target': '/usr/bin/python3',
            'needs': {
                'pkg_apt:python3',
            },
        },
    }

for name, data in node.metadata.get('apt/repos', {}).items():
    if 'items' in data:
        files['/etc/apt/sources.list.d/{}.list'.format(name)] = {
            'content_type': 'mako',
            'content': ("\n".join(sorted(data['items']))).format(
                os=node.os,
                os_release=supported_os[node.os][node.os_version[0]],
            ),
            'triggers': {
                'action:apt_update',
            },
        }
    elif 'uris' in data:
        uris = {
            x.format(
                os=node.os,
                os_release=supported_os[node.os][node.os_version[0]],
            ) for x in data['uris']
        }

        files['/etc/apt/sources.list.d/{}.sources'.format(name)] = {
            'source': 'deb822-sources',
            'content_type': 'mako',
            'context': {
                'data': data,
                'name': name,
                'os_release': supported_os[node.os][node.os_version[0]],
                'uris': uris,
            },
            'triggers': {
                'action:apt_update',
            },
        }

    if data.get('install_gpg_key', True):
        if 'items' in data:
            files['/etc/apt/sources.list.d/{}.list'.format(name)]['needs'] = {
                'file:/etc/apt/trusted.gpg.d/{}.list.asc'.format(name),
            }

        files['/etc/apt/trusted.gpg.d/{}.list.asc'.format(name)] = {
            'source': 'gpg-keys/{}.asc'.format(name),
            'triggers': {
                'action:apt_update',
            },
        }

for package, options in node.metadata.get('apt/packages', {}).items():
    pkg_apt[package] = options
