from bundlewrap.utils.scm import get_rev
from bundlewrap.utils.text import bold, red
from bundlewrap.utils.ui import io


@node_attribute
def needs_apply(node):
    if node.dummy:
        return False

    if node.os not in node.OS_FAMILY_UNIX:
        return True

    try:
        applied = node.run(
            'cat /var/lib/bundlewrap/last_apply_commit_id',
            may_fail=True,
        ).stdout.decode().strip()

        if not applied or applied != get_rev():
            return True
    except Exception as e:
        io.stderr(f'{red("!!!")}  {bold(node.name)}  {e!r}')

    return False


@node_attribute
def uses_bw_managed_ssl(node):
    if not node.has_bundle('nginx'):
        return False

    for vhost in node.metadata.get('nginx/vhosts', {}).values():
        if vhost['ssl'] not in (None, False, 'letsencrypt'):
            return True

    return False