{{- /* Inserts a text block into the HTML. See https://preliminary.istio.io/about/contribute/writing-a-new-topic/#embedding-preformatted-blocks for details */ -}}
{{- $downloadas := "" -}}
{{- if .Get 2 -}}
    {{- $downloadas = .Get 2 -}}
{{- end -}}

{{- $syntax := "" -}}
{{- $text := "" -}}
{{- $output := "" -}}

{{- if .Get 0 -}}
    {{- $lines := split (strings.TrimRight " " (trim .Inner "\n")) "\n" -}}

    {{- $line0 := index $lines 0 -}}
    {{- $indent := 0 -}}
    {{- if hasPrefix $line0 "                " -}}{{- $indent = 16 -}}
    {{- else if hasPrefix $line0 "            " -}}{{- $indent = 12 -}}
    {{- else if hasPrefix $line0 "        " -}}{{- $indent = 8 -}}
    {{- else if hasPrefix $line0 "    " -}}{{- $indent = 4 -}}
    {{- end -}}

    {{- $text = "" -}}
    {{- range $line := $lines -}}
        {{- if gt (len $line) $indent -}}
            {{- $l := substr $line $indent -}}
            {{- $text = printf "%s\n%s" $text $l -}}
        {{- else -}}
            {{- $text = printf "%s\n%s" $text $line -}}
        {{- end -}}
    {{- end -}}

    {{- $text = trim $text "\n" -}}
    {{- $syntax = .Get 0 -}}
    {{- $output = .Get 1 -}}
{{- else -}}
    {{- errorf "Text block does not specify a syntax (%s)" .Position -}}
{{- end -}}

{{- if (hasPrefix $text " ") -}}
    {{- errorf "Text blocks need to not be indented, or indented by a multiple of 4 spaces (%s)" .Position -}}
{{- end -}}

{{- if eq $syntax "bash" -}}
    {{- if not (hasPrefix $text "$") -}}
        {{- errorf "Text block specifies a bash syntax, but the first line of the block does not start with $ (%s)" .Position -}}
    {{- else -}}
        {{- if hasPrefix (trim $text " ") "$ cat <<EOF " -}}
            {{- $text = replace $text "$ cat" "cat" -}}
        {{- else if (or (hasPrefix (trim $text " ") "$ kubectl apply -f - <<EOF") (hasPrefix (trim $text " ") "$ kubectl create -f - <<EOF")) -}}
            {{- $text = replace $text "$ kubectl" "kubectl" -}}
        {{- else -}}
            {{- $syntax = "command" -}}
            {{- if $output -}}
                {{- $syntax = printf "command-output-as-%s" $output -}}
            {{- end -}}
        {{- end -}}
    {{- end -}}
{{- end -}}

{{- /* include a link to the special embedded @@ references so the links are statically checked as we build the site */ -}}
{{- $branch := .Site.Data.args.source_branch_name -}}
{{- $links := findRE "@(.*?)@" $text -}}
{{- range $link := $links -}}
    {{- $target := trim $link "@" -}}
    {{- if gt (len $target) 0 -}}
        {{- $href := printf "https://raw.githubusercontent.com/istio/istio/%s/%s" $branch $target -}}
        <a hidden style="display:none" href="{{- $href -}}">Hello</a>
    {{- end -}}
{{- end -}}

{{- if $downloadas -}}
<pre><code class='language-{{- $syntax -}}' data-downloadas='{{- $downloadas -}}'>{{- $text -}}</code></pre>
{{- else -}}
<pre><code class='language-{{- $syntax -}}'>{{- $text -}}</code></pre>
{{- end -}}
