#!/bin/sh -eu
occ="./occ"
current_nc_saml="$("${occ}" saml:config:get --output=json)"
prov_id="1"
if [ "${current_nc_saml}" = "{}" ] || [ "${current_nc_saml}" = "[]" ]; then
	prov_id="$("${occ}" saml:config:create)"
fi
# Gather variables
## When keycloak gets updated, /auth disappears
idp_entityid="https://sso.${DOMAIN}/auth/realms/master"
idp_sso_url="${idp_entityid}/protocol/saml"
## This one has no PEM headers or newlines
idp_x509cert="$(curl -s "${idp_entityid}/protocol/openid-connect/certs" | sed -E 's!.*RS256[^}]*x5c":\["([^"]+)".*!\1!')"

## PEM format
sp_x509cert="$(cat /saml/public.crt)"
## PEM format
sp_privatekey="$(cat /saml/private.key)"

# Actually set up Nextcloud
"${occ}" saml:config:set --no-interaction --no-ansi \
	--general-idp0_display_name="SAML Login" \
	--general-uid_mapping=username \
	--idp-entityId="${idp_entityid}" \
	--idp-singleLogoutService.url="${idp_sso_url}" \
	--idp-singleSignOnService.url="${idp_sso_url}" \
	--idp-x509cert="${idp_x509cert}" \
	--security-authnRequestsSigned=1 \
	--security-logoutRequestSigned=1 \
	--security-logoutResponseSigned=1 \
	--security-wantAssertionsSigned=1 \
	--security-wantMessagesSigned=1 \
	--saml-attribute-mapping-displayName_mapping=displayname \
	--saml-attribute-mapping-email_mapping=email \
	--saml-attribute-mapping-group_mapping=member \
	--saml-attribute-mapping-quota_mapping=quota \
	--sp-x509cert="${sp_x509cert}" \
	--sp-privateKey="${sp_privatekey}" \
	"${prov_id}"
# And set type, else it won't be active
"${occ}" config:app:set user_saml type --value saml
