#!/usr/bin/env python3
"""Generate a secure irreversable bcrypt hash compatible with palaceserver.
Uses cost factor 10, matching Go's bcrypt.DefaultCost and config.BcryptCost.

  pip install bcrypt
  ./scripts/pserver_bcrypt_hash.py 'your-password'

/etc/palacehostpass may contain either a bcrypt hash alone (shared secret; ~susr with
password only) or lines "username:bcrypt_hash" per operator (~susr with username:password).

Just make sure it's readable by the palace server process user.
"""

from __future__ import annotations

import argparse
import sys

try:
    import bcrypt
except ImportError:
    print("pserver_bcrypt_hash: install bcrypt: pip install bcrypt", file=sys.stderr)
    sys.exit(1)

# Must match bcrypt.DefaultCost in Go (10) otherwise it won't work!
ROUNDS = 10

def main() -> None:
    p = argparse.ArgumentParser(description="Print bcrypt hash for serverprefs.json / HOSTPASSWORD_HASH / --hostpass")
    p.add_argument("password", help="plaintext password (max 31 chars for Palace protocol)")
    args = p.parse_args()
    raw = args.password.encode("utf-8")
    if len(raw) > 72:
        print("pserver_bcrypt_hash: bcrypt limit is 72 bytes; Palace passwords are max 31.", file=sys.stderr)
        sys.exit(1)
    h = bcrypt.hashpw(raw, bcrypt.gensalt(rounds=ROUNDS))
    sys.stdout.write(h.decode("ascii") + "\n")

if __name__ == "__main__":
    print("(C) 2026 by Jonathan Kelley, http://ThePalace.app")
    main()
