#!/bin/bash

set -e -o pipefail

if [ -z "$1" ]; then
    echo "Usage: $0 export/to/path.md"
    exit 1
fi

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
TETRAGON_CHART="$SCRIPT_DIR/tetragon"

TMP_FILE=$(mktemp)
trap "rm $TMP_FILE" EXIT

# use the generated proto documentation as source
cp "$TETRAGON_CHART/README.md" $TMP_FILE

# cleanup the generated documentation for the website
# remove the title
sed -i'' -e '/^# tetragon$/d' $TMP_FILE
# remove the badges
sed -i'' -e '/^\!\[Version:/d' $TMP_FILE
# remove the "Helm chart for Tetragon mention"
sed -i'' -e '/^Helm chart for Tetragon$/d' $TMP_FILE
# remove unnecessary line
sed -i'' -e '/^----------------------------------------------$/d' $TMP_FILE
# remove autogenerated copyright
sed -i'' -e '/^Autogenerated from chart metadata using \[helm-docs /d' $TMP_FILE
# cleanup unecessary consecutive whitelines
sed -i'' -e '/^[[:space:]]*$/N;/^[[:space:]]*\n[[:space:]]*$/D' $TMP_FILE
# remove empty line at the end of the file (required for macOS, doesn't harm on Linux)
sed -i'' -e '${/^$/d;}' $TMP_FILE

# Cleanup backup file that might be created by macOS sed:
rm ${TMP_FILE}-e 2>/dev/null || true

# add a frontmatter and a small introduction
echo '---
title: "Helm chart"
description: "This reference is generated from the Tetragon Helm chart values."
weight: 2
---

{{< comment >}}
This page was generated with github.io/cilium/tetragon/install/kubernetes/tetragon/export-doc.sh,
please do not edit directly.
{{< /comment >}}

The Tetragon Helm chart source is available under
[github.io/cilium/tetragon/install/kubernetes/tetragon](https://github.com/cilium/tetragon/tree/main/install/kubernetes/tetragon)
and is distributed from the Cilium helm charts repository [helm.cilium.io](https://helm.cilium.io).

To deploy Tetragon using this Helm chart you can run the following commands:
```shell
helm repo add cilium https://helm.cilium.io
helm repo update
helm install tetragon cilium/tetragon -n kube-system
```

To use [the values available](#values), with `helm install` or `helm upgrade`, use `--set key=value`.' | cat - $TMP_FILE > $1
