#!/bin/sh

if [ -d ./pkgs ]
then
	rm -rf ./pkgs
fi

find ./ -type f -print | grep \\.decl | sort > tmplist1
cat tmplist1

TOTAL_PKGS=$(wc -l tmplist1)
COUNTER=0

cat tmplist1 | while read DECL
do
	COUNTER=$((COUNTER+1))
	./decl-to-pkg.sh "$DECL"
	echo "($COUNTER/$TOTAL_PKGS) $DECL"
done

find ./pkgs/ -type f -print | grep \\.txt | sort > pkglists

cat pkglists | while read PKGLIST
do
	OUTPUT="$(basename "$PKGLIST")"
	echo "version 2" > tmplist0
	cat "$PKGLIST" >> tmplist0
	SIG=$(openssl dgst -sha512 -sign ./private-key.pem tmplist0 | openssl enc -A -base64)
	head -n 1 tmplist0 > "$OUTPUT"
	echo "signature \"$AUTH_HOST\" \"$SIG\"" >> "$OUTPUT"
	tail -n +2 tmplist0 >> "$OUTPUT"
	rm tmplist0
	mv "$OUTPUT" "$PKGLIST"
done

rm tmplist1
rm pkglists
