#!/usr/bin/python3
"""
Create simplesamlphp IDP
"""
#
# 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/>.

import json
from argparse import SUPPRESS, ArgumentParser, FileType

from keycloak import KeycloakAdmin
from univention.config_registry import ConfigRegistry


def main():

    # load UCR
    ucr = ConfigRegistry()
    ucr.load()
    domain = ucr.get("domainname")
    ucs_idp_signing_cert = ucr.get("saml/idp/certificate/certificate")

    # 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-fqdn", default=f"ucs-sso-ng.{domain}", help="keycloak URL")
    parser.add_argument("--simplesamlphp-fqdn", help="SimpleSamlPHP FQDN", required=True)
    parser.add_argument(
        "--re-create", action="store_true", help="Delete IDP and authentication flow before create"
    )
    parser.add_argument("--idp-alias", default="ucs-simplesamlphp")
    parser.add_argument("--auth-flow-alias", default="ucs-simplesamlphp-first-login-flow")

    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=f"https://{args.keycloak_fqdn}",
        username=args.admin_username,
        password=password,
        realm_name=args.keycloak_realm,
        user_realm_name="master",
        verify=True,
    )

    # delete idp and auth flow
    if args.re_create:
        for idp in keycloak_session.get_idps():
            if idp["alias"] == args.idp_alias:
                keycloak_session.delete_idp(args.idp_alias)
        for flow in keycloak_session.get_authentication_flows():
            if flow["alias"] == args.auth_flow_alias:
                response = keycloak_session.raw_delete(
                    f"admin/realms/ucs/authentication/flows/{flow['id']}"
                )
                assert response.status_code == 204, response.text

    # add auth flow
    auth_flow_payload = {
        "alias": args.auth_flow_alias,
        "description": "Actions taken after first broker login with identity provider account, which is not yet linked to any Keycloak account",
        "providerId": "basic-flow",
        "topLevel": True,
        "builtIn": False,
    }
    path = f"admin/realms/{args.keycloak_realm}/authentication/flows"
    response = keycloak_session.raw_post(path, json.dumps(auth_flow_payload))
    flow_executions = keycloak_session.get_authentication_flow_executions(args.auth_flow_alias)
    if not flow_executions:
        keycloak_session.create_authentication_flow_execution(
            json.dumps({"provider": "idp-detect-existing-broker-user"}), args.auth_flow_alias
        )
        keycloak_session.create_authentication_flow_execution(
            json.dumps({"provider": "idp-auto-link"}), args.auth_flow_alias
        )
        flow_executions = keycloak_session.get_authentication_flow_executions(args.auth_flow_alias)
    for execution in flow_executions:
        execution["requirement"] = "REQUIRED"
        response = keycloak_session.raw_put(
            f"admin/realms/ucs/authentication/flows/{args.auth_flow_alias}/executions",
            json.dumps(execution),
        )
        assert response.status_code in [202], response.text

    # add simplesamlphp IDP
    cert = ""
    with open(ucs_idp_signing_cert, "r") as cert_fd:
        for line in cert_fd:
            if line == "-----BEGIN CERTIFICATE-----\n":
                break
        for line in cert_fd:
            if line == "-----END CERTIFICATE-----\n":
                break
            cert += line
    idp_payload = {
        "alias": args.idp_alias,
        "displayName": "UCS simplesamlphp",
        "providerId": "saml",
        "enabled": True,
        "updateProfileFirstLoginMode": "on",
        "linkOnly": False,
        "firstBrokerLoginFlowAlias": args.auth_flow_alias,
        "config": {
            "postBindingLogout": False,
            "postBindingResponse": False,
            "singleLogoutServiceUrl": f"https://{args.simplesamlphp_fqdn}/simplesamlphp/saml2/idp/SingleLogoutService.php",
            "nameIDPolicyFormat": "urn:oasis:names:tc:SAML:2.0:nameid-format:persistent",
            "entityId": f"https://{args.keycloak_fqdn}/realms/ucs",
            "backchannelSupported": False,
            "xmlSigKeyInfoKeyNameTransformer": "KEY_ID",
            "signatureAlgorithm": "RSA_SHA256",
            "idpEntityId": f"https://{args.simplesamlphp_fqdn}/simplesamlphp/saml2/idp/metadata.php",
            "useJwksUrl": True,
            "loginHint": False,
            "allowCreate": True,
            "authnContextComparisonType": "exact",
            "syncMode": "FORCE",
            "postBindingAuthnRequest": True,
            "singleSignOnServiceUrl": f"https://{args.simplesamlphp_fqdn}/simplesamlphp/saml2/idp/SSOService.php",
            "wantAuthnRequestsSigned": True,
            "wantAssertionsSigned": True,
            "addExtensionsElementWithKeyInfo": False,
            "principalType": "SUBJECT",
            "validateSignature": True,
            "signingCertificate": cert,
        },
    }
    keycloak_session.create_idp(idp_payload)

    # default IDP for browser flow
    flow_executions = keycloak_session.get_authentication_flow_executions("browser")
    for execution in flow_executions:
        if execution.get("providerId") == "identity-provider-redirector":
            execution["requirement"] = "ALTERNATIVE"
            response = keycloak_session.raw_put(
                "admin/realms/ucs/authentication/flows/browser/executions", json.dumps(execution)
            )
            assert response.status_code in [202], response.text
            try:
                conf = keycloak_session.get_authenticator_config(execution["authenticationConfig"])
            except KeyError:
                conf = {"alias": None, "config": {"defaultProvider": None}}
            conf["alias"] = args.idp_alias
            conf["config"]["defaultProvider"] = args.idp_alias
            try:
                keycloak_session.update_authenticator_config(conf, execution["authenticationConfig"])
            except KeyError:
                response = keycloak_session.raw_post(
                    f"admin/realms/ucs/authentication/executions/{execution['id']}/config",
                    json.dumps(conf),
                )
                assert response.status_code in [202, 201], response.text


if __name__ == "__main__":
    main()
