# Copyright 2021 Offensive Security
# SPDX-license-identifier: GPL-3.0-only

# Tests todo: should test that we refuse to touch a file if
# validataion by testparm fails. Not tested by unit tests as
# it requires to install samba-common-bin in the test env.

import os

from kali_tweaks.utils import (
    get_helper,
    run,
    run_as_root,
    say,
)


class SambaSetting:
    def __init__(self, config_file="/etc/samba/smb.conf"):
        self.config_file = config_file
        self.helper_script = get_helper("samba")

    def load(self):
        value = self.get_client_min_protocol()
        if value == "LANMAN1":
            value = "compat"
        elif value == "default":
            value = "secure"
        return {"hardening": value}

    def apply(self, config):
        say("Configuring Samba")
        if "hardening" in config:
            value = config["hardening"]
            if value == "compat":
                value = "LANMAN1"
            elif value == "secure":
                value = "default"
            else:
                raise NotImplementedError(f"'{value}' not supported")
            self.set_client_min_protocol(value)

    def get_client_min_protocol(self):
        cmd = f"{self.helper_script} {self.config_file} get"
        res = run(cmd)
        if res.returncode != 0:
            raise RuntimeError(f"Couldn't get samba config: {res.stderr}")
        value = res.stdout.strip()
        return value

    def set_client_min_protocol(self, value):
        print(f"> Setting client min protocol to: {value}")
        print(f"> Writing changes to {self.config_file}")
        cmd = f"{self.helper_script} {self.config_file} set {value}"
        # For unit tests: no need to be root
        if os.access(self.config_file, os.W_OK):
            res = run(cmd, interactive=True, log=False)
        else:
            res = run_as_root(cmd, interactive=True, log=False)
        if res.returncode != 0:
            raise RuntimeError("Couldn't set samba config")
