# 경로: modules/samba.py
import re
import subprocess

SAMBA_CONF = "/etc/samba/nas_smb.conf"

def update_samba_valid_users(users: list[str]):
    """
    valid users = user1 user2 user3 형태로 자동 갱신
    """
    users_str = " ".join(sorted(set(users)))

    with open(SAMBA_CONF, "r") as f:
        content = f.read()

    if re.search(r"^\s*valid users\s*=", content, re.MULTILINE):
        content = re.sub(
            r"^\s*valid users\s*=.*$",
            f"    valid users = {users_str}",
            content,
            flags=re.MULTILINE
        )
    else:
        # valid users 항목이 없으면 [STORAGE] 아래에 삽입
        content = re.sub(
            r"(\[STORAGE\][\s\S]*?)\n",
            r"\1\n    valid users = " + users_str + "\n",
            content,
            count=1
        )

    with open(SAMBA_CONF, "w") as f:
        f.write(content)

    # Samba 재시작
    subprocess.run(["systemctl", "restart", "smbd", "nmbd"], check=True)
