#!/usr/bin/env python3
"""Print SQL that creates one Guacamole admin.

Reads GUAC_ADMIN_USER and GUAC_ADMIN_PASSWORD from the environment.
No password is stored in this file. Nothing is written except SQL on stdout.
"""

import hashlib
import os
import re
import secrets
import sys

USERNAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_-]{2,31}$")
MIN_PASSWORD = 12


def main() -> int:
    username = os.environ.get("GUAC_ADMIN_USER", "").strip()
    password = os.environ.get("GUAC_ADMIN_PASSWORD", "")

    if not USERNAME_RE.fullmatch(username):
        print(
            "Set GUAC_ADMIN_USER to 3–32 letters, digits, _ or -.",
            file=sys.stderr,
        )
        return 1
    if len(password) < MIN_PASSWORD:
        print(
            f"Set GUAC_ADMIN_PASSWORD to at least {MIN_PASSWORD} characters.",
            file=sys.stderr,
        )
        return 1

    salt = secrets.token_bytes(32)
    # Guacamole hashes the password plus the uppercase hex of the salt.
    digest = hashlib.sha256(
        password.encode("utf-8") + salt.hex().upper().encode("utf-8")
    ).digest()
    salt_hex = salt.hex()
    hash_hex = digest.hex()

    print(
        f"""\
INSERT INTO guacamole_entity (name, type) VALUES ('{username}', 'USER');
INSERT INTO guacamole_user (entity_id, password_hash, password_salt, password_date)
SELECT
    entity_id,
    decode('{hash_hex}', 'hex'),
    decode('{salt_hex}', 'hex'),
    CURRENT_TIMESTAMP
FROM guacamole_entity WHERE name = '{username}' AND guacamole_entity.type = 'USER';

INSERT INTO guacamole_system_permission (entity_id, permission)
SELECT entity_id, permission::guacamole_system_permission_type
FROM (
    VALUES
        ('{username}', 'CREATE_CONNECTION'),
        ('{username}', 'CREATE_CONNECTION_GROUP'),
        ('{username}', 'CREATE_SHARING_PROFILE'),
        ('{username}', 'CREATE_USER'),
        ('{username}', 'CREATE_USER_GROUP'),
        ('{username}', 'ADMINISTER')
) permissions (username, permission)
JOIN guacamole_entity ON permissions.username = guacamole_entity.name AND guacamole_entity.type = 'USER';

INSERT INTO guacamole_user_permission (entity_id, affected_user_id, permission)
SELECT guacamole_entity.entity_id, guacamole_user.user_id, permission::guacamole_object_permission_type
FROM (
    VALUES
        ('{username}', '{username}', 'READ'),
        ('{username}', '{username}', 'UPDATE'),
        ('{username}', '{username}', 'ADMINISTER')
) permissions (username, affected_username, permission)
JOIN guacamole_entity          ON permissions.username = guacamole_entity.name AND guacamole_entity.type = 'USER'
JOIN guacamole_entity affected ON permissions.affected_username = affected.name AND affected.type = 'USER'
JOIN guacamole_user            ON guacamole_user.entity_id = affected.entity_id;
"""
    )
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
