if node.has_bundle('pyenv'):
    python_version = sorted(node.metadata.get('pyenv/python_versions'))[-1]
    python_path = f'/opt/pyenv/versions/{python_version}/bin/python'
else:
    python_path = '/usr/bin/python3'

users = {
    'homeassistant': {
        'home': '/var/opt/homeassistant',
    },
}

directories = {
    '/opt/homeassistant': {
        'owner': 'homeassistant',
    },
    '/var/opt/homeassistant': {
        'owner': 'homeassistant',
    },
}

files = {
    '/etc/systemd/system/homeassistant.service': {
        'triggers': {
            'action:systemd-reload',
            'svc_systemd:homeassistant:restart',
        },
    },
    '/usr/local/share/icinga/plugins/check_homeassistant_update': {
        'content_type': 'mako',
        'context': {
            'bearer': repo.vault.decrypt(node.metadata.get('homeassistant/api_secret')),
            'domain': node.metadata.get('homeassistant/domain'),
        },
        'mode': '0755',
    },
}

actions = {
    'homeassistant_create_virtualenv': {
        'command': f'sudo -u homeassistant virtualenv -p {python_path} /opt/homeassistant/venv/',
        'unless': 'test -d /opt/homeassistant/venv/',
        'needs': {
            'directory:/opt/homeassistant',
            'user:homeassistant',
        },
    },
    'homeassistant_install': {
        'command': 'sudo -u homeassistant /opt/homeassistant/venv/bin/pip install homeassistant',
        'unless': 'test -f /opt/homeassistant/venv/bin/hass',
        'needs': {
            'action:homeassistant_create_virtualenv',
            'pkg_apt:bluez',
            'pkg_apt:libffi-dev',
            'pkg_apt:libssl-dev',
            'pkg_apt:libjpeg-dev',
            'pkg_apt:zlib1g-dev',
            'pkg_apt:autoconf',
            'pkg_apt:build-essential',
            'pkg_apt:libopenjp2-7',
            'pkg_apt:libtiff6',
            'pkg_apt:libturbojpeg0-dev',
            'pkg_apt:tzdata',
        },
        'triggers': {
            'svc_systemd:homeassistant:restart',
        },
    },
}

svc_systemd = {
    'homeassistant': {
        'needs': {
            'action:homeassistant_install',
            'file:/etc/systemd/system/homeassistant.service',
        },
    },
}
