{#- Based on https://github.com/welpo/tabi/blob/7b00ed1d9dca5c529d2816c5b6679bfe600d63fc/templates/partials/content_security_policy.html -#}

<meta http-equiv="content-security-policy"
content="default-src 'none';
{%- if config.extra.csp -%}

	{#- Initialise a base script-src directive -#}
	{%- set script_src = "script-src 'self'" -%}

	{#- Initialise a base connect-src directive -#}
	{%- set connect_src = "connect-src 'self'" -%}

	{# Base logic for appending analytics domains #}
	{%- if config.extra.goatcounter %}
		{%- set goatcounter_host = config.extra.goatcounter.host | default(value='goatcounter.com') -%}
		{%- set goatcounter_url = "https://" ~ config.extra.goatcounter.user ~ "." ~ goatcounter_host ~ "/count" %}
		{%- set script_src = script_src ~ " " ~ goatcounter_url -%}
		{%- set connect_src = connect_src ~ " " ~ goatcounter_url -%}
	{%- endif %}


	{#- Append comments host if present -#}
	{%- if config.extra.comments -%}
		{%- set connect_src = connect_src ~ " " ~ "https://" ~ config.extra.comments.host -%}
	{%- endif -%}

	{#- Append WebSocket for Zola serve mode -#}
	{%- if config.mode == "serve" -%}
		{%- set connect_src = connect_src ~ " ws:" -%}
	{%- endif -%}

	{%- for domain in config.extra.csp -%}
		{%- if domain.directive == "connect-src" -%}
			{%- set configured_connect_src = domain.domains | join(sep=' ') -%}
			{%- set_global connect_src = connect_src ~ " " ~ configured_connect_src  -%}
			{%- continue -%}
		{%- endif -%}

		{%- if domain.directive == "script-src" -%}
			{%- set configured_script_src = domain.domains | join(sep=' ') -%}
			{%- set_global script_src = script_src ~ " " ~ configured_script_src  -%}
			{%- continue -%}
		{%- endif -%}

		{#- Handle directives that are not connect-src -#}
		{{ domain.directive }} {{ domain.domains | join(sep=' ') -}}

		{%- if not loop.last -%};{%- endif -%}
	{%- endfor -%}

	{#- Insert the generated connect-src -#}
	{{ ";" ~ connect_src }}

	{#- Insert the generated script-src -#}
	{{ ";" ~ script_src }}

{%- endif -%}" />
