#!/usr/bin/env python3
# Om Shri Ganeshaya Namah | Om Shri Durgayai Namah
import base64
import hashlib
import hmac
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path

PASS_FILE = Path("/etc/nxsupport/staff-password")
LISTEN_HOST = "127.0.0.1"
LISTEN_PORT = 5089


def _read_staff_password() -> str:
    try:
        return PASS_FILE.read_text(encoding="utf-8").strip()
    except FileNotFoundError:
        return ""


def _decode_b64(value: str) -> bytes:
    if not value:
        return b""
    return base64.b64decode(value)


def _is_authorized(payload: dict) -> bool:
    password = _read_staff_password()
    if not password:
        return False

    try:
        challenge = _decode_b64(str(payload.get("challenge", "")))
        salt = _decode_b64(str(payload.get("salt", "")))
        password_response = _decode_b64(str(payload.get("password_response", "")))
    except Exception:
        return False

    if not challenge or not salt or not password_response:
        return False

    phase1 = hashlib.sha256(password.encode("utf-8") + salt).digest()
    expected = hashlib.sha256(phase1 + challenge).digest()
    return hmac.compare_digest(expected, password_response)


class Handler(BaseHTTPRequestHandler):
    def log_message(self, fmt: str, *args):
        return

    def _send_json(self, code: int, payload: dict):
        body = json.dumps(payload).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        if self.path == "/health":
            self._send_json(200, {"ok": True})
            return
        self._send_json(404, {"ok": False, "error": "not found"})

    def do_POST(self):
        if self.path != "/api/auth/master-password/validate":
            self._send_json(404, {"ok": False, "error": "not found"})
            return

        try:
            length = int(self.headers.get("Content-Length", "0"))
        except ValueError:
            length = 0
        raw = self.rfile.read(length) if length > 0 else b"{}"
        try:
            payload = json.loads(raw.decode("utf-8"))
            if not isinstance(payload, dict):
                payload = {}
        except Exception:
            payload = {}

        allow = _is_authorized(payload)
        self._send_json(200, {"allow": allow})


if __name__ == "__main__":
    server = HTTPServer((LISTEN_HOST, LISTEN_PORT), Handler)
    server.serve_forever()
