#!/bin/bash

set -e

BASEDIR="$(pwd)"
OUTFILE="$BASEDIR/parser/eventtypes/allschema.gen.go"
PKGFILE="$BASEDIR/tmp/packages.txt"
LINES="$BASEDIR/tmp/lines.txt"

if [ ! -d "$BASEDIR/tmp" ]; then
	mkdir -p "$BASEDIR/tmp"
else
	rm -f -- "$PKGFILE" "$LINES"
fi

cd ../schema
rm -rf tmp || true
make jenkins-metadata-generation
cd tmp/metadata

while read FILENAME;
do
	echo "$FILENAME"
	pkgdir=$(dirname "$FILENAME")
	pkg=$(basename "$pkgdir")
	typename="$(cat "$FILENAME" | jq -r .event_type)"
	echo " $pkgdir, $pkg, $typename"
	echo "    \"code.justin.tv/eventbus/schema/pkg/$pkg\"" >> "$PKGFILE"
	echo "\"$typename\": func() eventbus.Message { return new(${pkg}.${typename}) }," >> "$LINES"

done < <(find . -iname '*.json' | sort)

packages="$(cat "$PKGFILE" | sort | uniq )"
lines="$(cat "$LINES")"

cat > "$OUTFILE" <<EOF
package eventtypes

import (
    $packages
)

type Builder func() eventbus.Message
var  MessageBuilders = map[string]Builder {
     $lines
}
EOF
cd $BASEDIR
goimports -w ./parser/eventtypes || gofmt -w ./parser/eventtypes