#!/bin/bash

set -eu

rootdir=$(readlink -f "$(dirname "$0")/..")

echo "$rootdir"

mkdir -p "$rootdir/public/groups"
mkdir -p "$rootdir/public/keys"

echo "<h1>Gruppen</h1>" > public/list.html

for grouppath in "$rootdir/groups/"*; do
	group=$(basename "$grouppath")
	echo "Group $group"
	echo "<li><a href=\"groups/$group\">$group</a></li>" >> public/list.html
	echo "# Gruppe $group https://pages.freifunk-stuttgart.net/firmware/ssh-keys" > "$rootdir/public/groups/$group"
	for memberpath in "$rootdir/groups/$group/"*; do
		member=$(basename "$memberpath")
		echo "  Member $member"
		memberkeyfile="$rootdir/keys/$member"
		if [ ! -f "$memberkeyfile" ]; then
			echo "  ERROR: Could not find keys for '$member' in '$memberkeyfile'"
			exit 1
		fi
		echo "# $member" >> "$rootdir/public/groups/$group"
		cat "$rootdir/keys/$member" >> "$rootdir/public/groups/$group"
	done
done

echo "<h1>Nutzer*innen</h1>" >> public/list.html
for keypath in "$rootdir/keys/"*; do
	user=$(basename "$keypath")
	echo "<li><a href=\"keys/$user\">$user</a></li>" >> public/list.html
	echo "# $user" >> "$rootdir/public/keys/$user"
	cat "$rootdir/keys/$member" >> "$rootdir/public/keys/$user"
done
