#!/bin/sh
TARGET_DIRECTORY=${TARGET_DIRECTORY?-out}
INPUT=$1
_BASEDIR=`basename $INPUT`
PACK=${_BASEDIR%.*}
OUTNAME="$(sha256sum "$1" | awk '{ print $1 }').${1##*.}"
cp "$INPUT" "$TARGET_DIRECTORY/$OUTNAME"
echo "Writing card '$PACK'..."
if [[ $2 == '-' && -z $3 ]]; then
	cp "${INPUT%.*}.json" "$TARGET_DIRECTORY/$PACK.json"
	exit;
fi
printf "{\"$PACK\":{" > "$TARGET_DIRECTORY/$PACK.json"
printf "\"\":{" >> "$TARGET_DIRECTORY/$PACK.json"
printf "\"--usercard-image\":\"$OUTNAME\"" >> "$TARGET_DIRECTORY/$PACK.json"
if [ ! -z $2 ]; then
	[ $2 != '-' ] && printf ",\"--usercard-color\":\"$2\"" >> "$TARGET_DIRECTORY/$PACK.json"
	if [ ! -z $3 ]; then
		[ $3 != '-' ] && printf ",\"--main-text\":\"$3\"" >> "$TARGET_DIRECTORY/$PACK.json"
		if [ ! -z $4 ]; then
			printf ",\"--usercard-outline\":\"$4\"" >> "$TARGET_DIRECTORY/$PACK.json"
		fi
	fi
fi
printf "}}}" >> "$TARGET_DIRECTORY/$PACK.json"