#!/usr/bin/env python3
"""
admin-set-password — set the owner password for vendora-admin.

Usage:
    sudo /opt/vendora_sbc/tools/admin-set-password
        (interactive — prompts twice for password)

    echo 'mysecret' | sudo /opt/vendora_sbc/tools/admin-set-password --stdin
        (non-interactive — reads single password from stdin)

The password hash is stored in /var/lib/vendora/state.db (config table, key
'owner_password_hash') using scrypt with a random per-password salt.

Requires root (must write to the SQLite DB owned by root).
"""

from __future__ import annotations

import argparse
import getpass
import os
import sys
import time
from pathlib import Path

sys.path.insert(0, "/opt/vendora_sbc/services")

from common import db as vdb  # noqa: E402

# Reuse the same scrypt parameters as vendora_admin.py
sys.path.insert(0, "/opt/vendora_sbc/services/admin")
from vendora_admin import hash_password  # noqa: E402


def read_password_stdin() -> str:
    data = sys.stdin.read()
    # Take first line, strip trailing whitespace/newlines
    return data.splitlines()[0].rstrip() if data else ""


def prompt_password_twice() -> str:
    while True:
        p1 = getpass.getpass("New owner password: ")
        if not p1:
            print("Empty password — try again.", file=sys.stderr)
            continue
        if len(p1) < 6:
            print("Password too short (min 6 chars).", file=sys.stderr)
            continue
        p2 = getpass.getpass("Confirm: ")
        if p1 != p2:
            print("Passwords don't match — try again.", file=sys.stderr)
            continue
        return p1


def main() -> int:
    ap = argparse.ArgumentParser(description="Set the Vendora admin owner password")
    ap.add_argument(
        "--stdin", action="store_true",
        help="Read password from stdin (single line) instead of prompting",
    )
    args = ap.parse_args()

    if os.geteuid() != 0:
        print("This tool must be run as root (use sudo).", file=sys.stderr)
        return 1

    if args.stdin:
        password = read_password_stdin()
        if not password or len(password) < 6:
            print("Password from stdin must be at least 6 chars.", file=sys.stderr)
            return 2
    else:
        password = prompt_password_twice()

    h = hash_password(password)
    now = int(time.time())

    try:
        conn = vdb.open_db(readonly=False)
        try:
            conn.execute(
                "INSERT INTO config(key, value, updated_at) VALUES ('owner_password_hash', ?, ?) "
                "ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at",
                (h, now),
            )
            conn.commit()
        finally:
            conn.close()
    except Exception as e:
        print(f"DB error: {e}", file=sys.stderr)
        return 3

    print("Owner password set. You can now log in at http://10.0.10.1:8080/")
    return 0


if __name__ == "__main__":
    sys.exit(main())
