#!/usr/bin/env python3
#
# This hook reads snap options set via `snap set`, writes them to
# landscape-client.conf, and then unsets them.
# The landscape-client.conf file is the single source of truth,
# snap options are transient inputs only.

import os
import subprocess

from landscape.client.deployment import Configuration


def _snapctl(*args):
    snapctl = subprocess.run(["snapctl", *args], 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([])

# Each entry in config_entries maps a snap option to a landscape
# config key, with an optional mapping applied to the value.
config_entries = [
    ("account-name", "account_name", None),
    ("computer-title", "computer_title", None),
    ("url", "url", None),
    ("ping-url", "ping_url", None),
    ("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),
    ("apt-update-timeout", "apt_update_timeout", None),
    ("cloud", "cloud", None),
]

# Deprecated keys kept for backward compatibility.
# New keys take precedence.
legacy_config_entries = [
    ("landscape-url", "url", lambda url: f"{url}/message-system"),
    ("landscape-ping-url", "ping_url", lambda url: f"{url}/ping"),
]

changed = set()
for snapctl_key, landscape_key, mapping_fn in [*legacy_config_entries, *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()

# May contain sensitive values (e.g. registration_key); keep it locked down.
# config.write() doesn't reset permissions on an existing file, but this is
# defense-in-depth for cases where the underlying file didn't already exist.
os.chmod(config.get_config_filename(), 0o600)

# Unset changed keys so that on the next run we know what has changed.
if changed:
    _snapctl("unset", *changed)
