#!/bin/bash

# shellcheck disable=SC2119

# Usage: ./app-catalogue.sh
#
# Gather metadata from Co-op Cloud apps in $ABRA_DIR/apps (default
# ~/.abra/apps), and format it as a Markdown table for this page:
# https://docs.cloud.autonomic.zone/apps/

stack_dir="${ABRA_DIR:-$HOME/.abra}/apps/"

cd "$stack_dir" || exit

# load all README files into ENV_FILES array
mapfile -t readmes < <(find -L . -name "README.md")
# FIXME 3wc: requires bash 4, use for loop instead

base_url="https://git.autonomic.zone/coop-cloud"

cat_apps=()
cat_development=()
cat_utilities=()
cat_graveyard=()

get_var() {
	echo "$1" | grep "$2" | sed 's/^[^:]*: //'
}

# shellcheck disable=SC2120
trim() {
	# accept input as argument or from STDIN, see here:
	# https://zwbetz.com/passing-input-to-a-bash-function-via-arguments-or-stdin/
	# shellcheck disable=SC2155
	local input="$([[ -p /dev/stdin ]] && cat - || echo "$@")"
	[[ -z "$input" ]] && return 1
	echo "$input" | tr -d ' '
}

# shellcheck disable=SC2120
prettify() {
	# as above
	# shellcheck disable=SC2155
	local input="$([[ -p /dev/stdin ]] && cat - || echo "$@")"
	[[ -z "$input" ]] && return 1

	echo "$input" | sed -e 's/Yes/✅/' -e 's/No/❌/' -e 's/N\/A/⛔/'
}

for readme in "${readmes[@]}"; do
	type="$(basename "${readme%README.md}")"
	if [ "$type" = "example" ]; then
		continue
	fi
	title="$(grep '^# ' "$type/README.md" | sed 's/^# //' )"
	# find section between 'metadata' and 'endmetadata' comments
	metadata="$(awk '/-- metadata --/,/-- endmetadata --/' "$type/README.md")"
	status="$(get_var "$metadata" "Status")"
	category="$(get_var "$metadata" "Category" | cut -d',' -f2 | trim)"

	if [ -z "$category" ]; then
		echo "ERROR: missing category for $type"
		continue
	fi

	image="$(get_var "$metadata" "Image" | cut -d',' -f2 | trim)"
	healthcheck="$(get_var "$metadata" "Healthcheck" | prettify)"
	backups="$(get_var "$metadata" "Backups" | prettify)"
	email="$(get_var "$metadata" "Email" | prettify)"
	tests="$(get_var "$metadata" "Tests" | prettify)"
	sso="$(get_var "$metadata" "SSO" | prettify)"

	row="| [$title]($base_url/$type) | $status | $image | $healthcheck | $backups | $email | $tests | $sso |"

	category_lower="$(echo "$category" | tr '[:upper:]' '[:lower:]')"
	eval "cat_$category_lower+=( '$row' )"
done

headers="
| **Name** | **Status** | **Image** | **Healtcheck** | **Backups** | **Email** | **CI** | **Single-Sign-On** |
| --- | --- | --- | --- | --- | --- | --- | --- |"

echo "## Applications"
echo "$headers"
printf '%s\n' "${cat_apps[@]}" | sort

echo

echo "## Developer tools"
echo "$headers"
printf '%s\n' "${cat_development[@]}" | sort

echo

echo "## Utilities"
echo "$headers"
printf '%s\n' "${cat_utilities[@]}" | sort

echo

echo "## Graveyard"
echo "$headers"
printf '%s\n' "${cat_graveyard[@]}" | sort