# Register the client again if coreapp.toml's [sso] changed it (its
# callback, PKCE, or how it sends its secret); Authelia restarts only then
IDP=/federated/apps/authelia/data/config/idproviders.yml
BLOCK="$(sed -n '/^      ### coreapp-{{NAME}} begin$/,/^      ### coreapp-{{NAME}} end$/p' "$IDP")"
if ! grep -qxF "          - 'https://{{NAME}}.$DOMAIN{{SSO_CALLBACK}}'" <<< "$BLOCK" \
    || ! grep -qxF "        token_endpoint_auth_method: '{{SSO_TOKEN_AUTH}}'" <<< "$BLOCK" \
    || ! grep -qxF "        $(echo "{{SSO_PKCE}}" | head -1)" <<< "$BLOCK" \
    || [ "$(grep -c pkce_challenge_method <<< "$BLOCK")" != "$(echo "{{SSO_PKCE}}" | grep -c pkce_challenge_method)" ]; then
  . /federated/services/{{NAME}}/needs/sso/setup
fi
unset BLOCK
# Keep the copy of its Authelia client current (apps installed before
# copies were kept get one); Authelia's start restores clients from these
IDP=/federated/apps/authelia/data/config/idproviders.yml
COPY=/federated/apps/{{NAME}}/.{{NAME}}.oidc-client.yml
if grep -qx '      ### coreapp-{{NAME}} begin' "$IDP"; then
  sed -n '/^      ### coreapp-{{NAME}} begin$/,/^      ### coreapp-{{NAME}} end$/p' "$IDP" > "$COPY"
  chmod 600 "$COPY"
fi
unset IDP COPY
