#!/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 random import randint
from time import sleep
from typing import List
from urllib.parse import urlparse

from keycloak import KeycloakAdmin
from keycloak.exceptions import KeycloakGetError
from univention.config_registry import ConfigRegistry


def update_redirect_uris(
    keycloak_session: KeycloakAdmin,
    client_name: str,
    redirect_uris: List[str],
) -> None:
    client_id = keycloak_session.get_client_id(client_name)
    if not client_id:
        print(f"{client_name} not found, not update redirect uris")
        return
    client_config = keycloak_session.get_client(client_id)
    for uri in redirect_uris:
        if uri not in client_config["redirectUris"]:
            client_config["redirectUris"].append(uri)
        web_origin = f"{urlparse(uri).scheme}://{urlparse(uri).netloc}"
        if web_origin not in client_config["webOrigins"]:
            client_config["webOrigins"].append(web_origin)
    keycloak_session.update_client(client_id, client_config)


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",
                }
            }
        )
    if redirect_uris == ["https://*", "http://*"]:
        client_payload.update(
            {
                "webOrigins": ["*"],
            },
        )
    keycloak_session.create_client(payload=client_payload, skip_exists=True)

    def work_around_issue_17() -> None:
        # https://git.knut.univention.de/univention/components/keycloak-app/-/issues/17
        # We need to fix the CSP to be able to run embedded in the portal
        ucr = ConfigRegistry()
        ucr.load()
        domain = ucr.get("domainname")
        keycloak_session.update_realm(
            "ucs",
            {
                "browserSecurityHeaders": {
                    "contentSecurityPolicy": f"frame-src 'self'; frame-ancestors 'self' https://*.{domain}; object-src 'none';"
                }
            },
        )

    work_around_issue_17()


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="store",
        nargs="*",
        help="Valid Redirect URIs for client",
        default=["https://*", "http://*"],
    )
    parser.add_argument(
        "--recreate-client",
        action="store_true",
        help="Delete an already existing client and create a new one",
    )
    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")

    # 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,
    )
    if args.recreate_client:
        keycloak_session.delete_client(keycloak_session.get_client_id(args.client_id))
    create_client(
        keycloak_session,
        args.client_id,
        args.redirect_uris,
        direct_access=args.direct_access,
    )
    if set(args.redirect_uris) != set(["https://*", "http://*"]):
        try:
            update_redirect_uris(keycloak_session, args.client_id, args.redirect_uris)
        except KeycloakGetError:
            # sometimes, for unknown reasons we get
            #  File "/usr/lib/python3/dist-packages/keycloak/keycloak_admin.py", line 888, in update_client
            #  return raise_error_from_response(data_raw, KeycloakGetError, expected_codes=[204])
            #  File "/usr/lib/python3/dist-packages/keycloak/exceptions.py", line 108, in raise_error_from_response response_body=response.content)
            #  keycloak.exceptions.KeycloakGetError: 409: b'{"errorMessage":"Client already exists"}'
            # just try it again
            sleep(randint(3, 10))
            update_redirect_uris(keycloak_session, args.client_id, args.redirect_uris)


if __name__ == "__main__":
    main()
