#!/usr/bin/env python3

import os
import subprocess

from landscape.client.deployment import Configuration


def _snapctl(action, setting):
    snapctl = subprocess.run(
        ["snapctl", action, setting],
        capture_output=True,
        text=True,
    )
    return snapctl.stdout

def update_ssl_cert(cert: str) -> str | None:
    cert_path = os.path.join(os.getenv("SNAP_COMMON"), "etc/ssl/certs")
    if not os.path.isdir(cert_path):
        os.makedirs(cert_path)

    cert_path = os.path.join(cert_path, "ssl-public-key.crt")
    with open(cert_path, 'w') as f:
        f.write(cert)

    return str(cert_path)

config = Configuration()
config.load([])

config_entries = [
    # (snapctl key, landscape client config key, mapping function)
    ("account-name", "account_name", None),
    ("computer-title", "computer_title", None),
    ("landscape-url", "url", lambda url: f"{url}/message-system"),
    ("landscape-ping-url", "ping_url", lambda url: f"{url}/ping"),
    ("ssl-public-key", "ssl_public_key", update_ssl_cert),
    ("log-level", "log_level", None),
    ("script-users", "script_users", None),
    ("manager-plugins", "manager_plugins", None),
    ("monitor-plugins", "monitor_plugins", None),
    ("access-group", "access_group", None),
    ("registration-key", "registration_key", None),
    ("ping-interval", "ping_interval", None),
    ("urgent-exchange-interval", "urgent_exchange_interval", None),
    ("snap-monitor-interval", "snap_monitor_interval", None),
    ("package-monitor-interval", "package_monitor_interval", None),
    ("flush-interval", "flush_interval", None),
    ("exchange-interval", "exchange_interval", None),
    ("apt-update-interval", "apt_update_interval", None),
    ("cloud", "cloud", None),
]

changed = set()
for snapctl_key, landscape_key, mapping_fn in config_entries:
    value = _snapctl("get", snapctl_key).strip()
    if not value:
        # empty, value has not changed
        continue

    if mapping_fn:
        value = mapping_fn(value)

    setattr(config, landscape_key, value)
    changed.add(snapctl_key)

config.write()

# unset the values from snapctl so that in the next run
#  we know what has changed
# the landscape-client.conf file is still the main source of truth
_snapctl("unset", " ".join(changed))
