#!/usr/bin/env python3
"""WSGI WebDAV server with Basic auth."""
import os
from wsgidav.wsgidav_app import WsgiDAVApp
from wsgidav.dc.abstract_dc import AbstractDomainController
from cheroot import wsgi

HTPASSWD_FILE = "/etc/wsgidav/htpasswd"

class HtpasswdDomainController(AbstractDomainController):
    def __init__(self, wsgidav_app, config):
        super().__init__(wsgidav_app, config)
        self.users = {}
        self._load_htpasswd()
    
    def _load_htpasswd(self):
        with open(HTPASSWD_FILE) as f:
            for line in f:
                line = line.strip()
                if ":" in line:
                    user, _ = line.split(":", 1)
                    self.users[user] = True
    
    def get_domain_realm(self, path_info, environ):
        return "WebDAV"
    
    def require_authentication(self, path_info, environ):
        return True
    
    def is_realm_user(self, realm, username, password):
        import subprocess
        result = subprocess.run(
            ["htpasswd", "-v", "-b", HTPASSWD_FILE, username, password],
            capture_output=True, text=True
        )
        return result.returncode == 0

config = {
    "host": "0.0.0.0",
    "port": 80,
    "root_path": "/data",
    "provider_mapping": {"/": "/data"},
    "http_authenticator": {
        "domain_controller": HtpasswdDomainController,
    },
    "verbose": 1,
    "enable_loggers": [],
    "middleware_stack": None,
}

app = WsgiDAVApp(config)

server = wsgi.Server(
    (config["host"], config["port"]),
    app,
    numthreads=10,
    request_queue_size=100,
)
print(f"WebDAV server starting on {config['host']}:{config['port']}")
server.start()
