# Info: KCL Cosmian KMS task schemas for provisioning (Provisioning)
# Author: Provisioning System
# Release: 0.0.1
# Date: 2025-07-24

import regex

schema User:
    """
    User settings for KMS
    """
    name: str
    group: str = name
    home?: str = "/home/${name}"

schema Database:
    """
    KMS Database configuration
    """
    typ: "sqlite" | "mysql" | "postgresql" | "redis" = "sqlite"
    host?: str = "127.0.0.1"
    port?: int = 5432 if typ == "postgresql" else 3306 if typ == "mysql" else 6379 if typ == "redis" else Undefined
    database?: str = "kms"
    username?: str
    password?: str
    path?: str = "/var/lib/kms/kms.db" if typ == "sqlite" else Undefined
    ssl_mode?: "require" | "disable" = "disable"
    
    check:
        typ == "sqlite" or username != Undefined and len(username) > 0, "Database username required for ${typ}"
        typ == "sqlite" or password != Undefined and len(password) > 0, "Database password required for ${typ}"
        typ == "sqlite" or host != Undefined and len(host) > 0, "Database host required for ${typ}"

schema Auth:
    """
    Authentication configuration
    """
    enabled: bool = False
    jwt_issuer_uri?: str
    jwks_uri?: str
    jwt_audience?: str
    
    check:
        not enabled or jwt_issuer_uri != Undefined and len(jwt_issuer_uri) > 0, "JWT issuer URI required when auth enabled"

schema CosmianKMS:
    """
    Cosmian KMS server configuration
    """
    name: str = "kms"
    version: str
    run_user: User = {
        name = "kms"
    }
    work_path: str = "/var/lib/kms"
    config_path: str = "/etc/cosmian"
    config_file: str = "kms.toml"
    run_path: str = "/usr/local/bin/cosmian_kms"
    bind_addr: str = "0.0.0.0"
    port: int = 9998
    database: Database = {
        typ = "sqlite"
    }
    auth: Auth = {
        enabled = False
    }
    log_level: "trace" | "debug" | "info" | "warn" | "error" = "info"
    fips_mode: bool = False
    tls_enabled: bool = False
    cert_file?: str
    key_file?: str
    ca_cert_file?: str
    
    check:
        1 <= port <= 65535, "port must be between 1 and 65535, inclusive"
        len(run_user.name) > 0, "Check run_user name"
        len(work_path) > 0, "Check work_path"
        len(config_path) > 0, "Check config_path"
        not tls_enabled or cert_file != Undefined and len(cert_file) > 0, "cert_file required when TLS enabled"
        not tls_enabled or key_file != Undefined and len(key_file) > 0, "key_file required when TLS enabled"
        not tls_enabled or (regex.match(cert_file, "^\/.*\.(pem|crt)$") if cert_file != Undefined else True), \
            "cert_file should be absolute path with .pem or .crt extension"
        not tls_enabled or (regex.match(key_file, "^\/.*\.(pem|key)$") if key_file != Undefined else True), \
            "key_file should be absolute path with .pem or .key extension"