#!/usr/bin/env python3
import getpass
import hashlib
import os
import secrets
import sys

import pymysql


def load_env(path="/etc/conf.d/crm"):
    env = {}
    try:
        with open(path, "r", encoding="utf-8") as fh:
            for line in fh:
                line = line.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                key, value = line.split("=", 1)
                env[key] = value.strip().strip('"').strip("'")
    except FileNotFoundError:
        pass
    return env


CFG = load_env()


def cfg(name, default=""):
    return os.environ.get(name) or CFG.get(name) or default


def db():
    return pymysql.connect(
        host=cfg("MYSQL_HOST"),
        port=int(cfg("MYSQL_PORT", "3306")),
        user=cfg("MYSQL_USER"),
        password=cfg("MYSQL_PASSWORD"),
        database=cfg("MYSQL_DATABASE"),
        charset="utf8mb4",
        autocommit=True,
        cursorclass=pymysql.cursors.DictCursor,
        connect_timeout=5,
    )


def hash_password(password):
    iterations = 200000
    salt = secrets.token_hex(16)
    digest = hashlib.pbkdf2_hmac("sha256", password.encode(), salt.encode(), iterations).hex()
    return f"pbkdf2_sha256${iterations}${salt}${digest}"


def ensure_schema(conn):
    with conn.cursor() as cur:
        cur.execute(
            """
            create table if not exists crm_users (
                id bigint unsigned not null auto_increment primary key,
                username varchar(128) not null unique,
                password_hash varchar(255) not null,
                display_name varchar(255) not null default '',
                role varchar(64) not null default 'agent',
                active tinyint(1) not null default 1,
                last_login timestamp null,
                created_at timestamp not null default current_timestamp
            ) charset=utf8mb4
            """
        )


def main():
    if len(sys.argv) < 3 or sys.argv[1] not in {"add", "passwd"}:
        print("usage: crm-user add USER [DISPLAY_NAME] | crm-user passwd USER", file=sys.stderr)
        raise SystemExit(2)
    action, username = sys.argv[1], sys.argv[2]
    password = getpass.getpass("password: ")
    if password != getpass.getpass("repeat: "):
        print("passwords differ", file=sys.stderr)
        raise SystemExit(1)
    display = sys.argv[3] if len(sys.argv) > 3 else username
    with db() as conn:
        ensure_schema(conn)
        with conn.cursor() as cur:
            if action == "add":
                cur.execute(
                    "insert into crm_users(username,password_hash,display_name) values(%s,%s,%s)",
                    (username, hash_password(password), display),
                )
            else:
                cur.execute(
                    "update crm_users set password_hash=%s where username=%s",
                    (hash_password(password), username),
                )
    print("ok")


if __name__ == "__main__":
    main()

