#!/usr/bin/python3
"""
Create keycloak clients for school ui-* modules
"""
#
# Copyright 2022 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this program provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use this program under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from argparse import SUPPRESS, ArgumentParser, FileType
from typing import List

from keycloak import KeycloakAdmin
from univention.config_registry import ConfigRegistry


def create_client(
    keycloak_session: KeycloakAdmin,
    client_id: str,
    redirect_uris: List[str],
    direct_access: bool = False,
) -> None:
    client_payload = {
        "clientId": client_id,
        "enabled": True,
        "protocol": "openid-connect",
        "publicClient": True,
        "redirectUris": redirect_uris,
        "consentRequired": False,
        "directAccessGrantsEnabled": direct_access,
        "protocolMappers": [
            {
                "name": "client_id",
                "protocol": "openid-connect",
                "protocolMapper": "oidc-hardcoded-claim-mapper",
                "config": {
                    "claim.value": client_id,
                    "userinfo.token.claim": False,
                    "id.token.claim": False,
                    "access.token.claim": True,
                    "claim.name": "client_id",
                    "jsonType.label": "String",
                },
            }
        ],
    }
    if not direct_access:
        client_payload.update(
            {
                "attributes": {
                    "pkce.code.challenge.method": "S256",
                }
            }
        )
    keycloak_session.create_client(payload=client_payload, skip_exists=False)


def main():

    # load UCR
    ucr = ConfigRegistry()
    ucr.load()
    domain = ucr.get("domainname")

    # parse arguments
    parser = ArgumentParser(description="create ui-users keycloak client")
    parser.add_argument(
        "--admin-username",
        default="Administrator",
        help="keycloak admin account username",
    )
    parser.add_argument("--admin-password", help=SUPPRESS)
    parser.add_argument(
        "--admin-pwdfile",
        metavar="FILE",
        type=FileType("r", encoding="UTF-8"),
        help="file containing the password",
    )
    parser.add_argument("--keycloak-realm", default="ucs", help="keycloak realm")
    parser.add_argument(
        "--keycloak-url", default=f"https://ucs-sso-ng.{domain}", help="keycloak URL"
    )
    parser.add_argument("--client-id", default="ucs-school-ui-users", help="client id")
    parser.add_argument(
        "--direct-access",
        action="store_true",
        help='use "Resource Owner Password Flow" (directAccessGrantsEnabled) instead of "Authorization Code Flow with PKCE" for client',
    )
    parser.add_argument(
        "--redirect-uris", action="append", help="Valid Redirect URIs for client"
    )
    args = parser.parse_args()

    password = None
    if args.admin_pwdfile:
        password = args.admin_pwdfile.read().strip()
    if args.admin_password:
        password = args.admin_password
    if password is None:
        parser.error("provide --admin-pwdfile")
    if args.redirect_uris is None:
        redirect_uris = ["https://*", "http://*"]

    # get keycloak session
    keycloak_session = KeycloakAdmin(
        server_url=args.keycloak_url,
        username=args.admin_username,
        password=password,
        realm_name=args.keycloak_realm,
        user_realm_name="master",
        verify=True,
    )
    create_client(
        keycloak_session, args.client_id, redirect_uris, direct_access=args.direct_access
    )


if __name__ == "__main__":
    main()
