#!/bin/sh
# convert meson wrap files into makefiles for compatibility reasons
F="$1"
S="$"
if [ -z "$F" ]; then
	echo "Usage: acr-wrap foo.wrap > foo.mk"
	exit 1
fi
(
echo "# This file is autogenerated by acr-wrap"
echo
NAME=""
while : ; do
	read LINE
	[ $? != 0 ] && break
	echo "$LINE" | grep -q =
	if [ $? = 0 ]; then
		if [ -z "${NAME}" ]; then
			echo "malformed"
			break
		fi
		echo ${LINE} |grep '^#' && continue
		LINE=`echo "$LINE"|sed -e 's, ,,g'`
		echo "WRAP_${NAME}_${LINE}" | sed -e 's/=/:=/g'
		eval "export WRAP_${LINE}"
	else
		echo "$LINE" | grep -q '^\['
		if [ $? = 0 ]; then
			NAME=$(echo "$LINE" |sed -e 's,-,_,g' -e 's,\[,,g' -e 's,\],,g')
		fi
	fi
done

WRAP_name=`echo ${WRAP_directory}|sed -e 's/-/-/g'`

cat <<EOF

.PHONY: ${WRAP_directory}_clean ${WRAP_directory}_all

${WRAP_directory}:
EOF
if [ -n "$WRAP_revision" ]; then
	echo "	if [ ! -d \"${WRAP_directory}\" -o \"${WRAP_revision}\" != \"${S}(shell cd ${WRAP_directory} 2>/dev/null && git rev-parse HEAD)\" ]; then rm -rf \"${WRAP_directory}\"; ${S}{MAKE} ${WRAP_directory}_all; fi"
else
	echo "	${S}{MAKE} ${S}{MAKE_FLAGS} ${WRAP_directory}_all"
fi

cat <<EOF

${WRAP_directory}_all:
EOF
GIT_FLAGS=""
if [ -n "${WRAP_source_url}" ]; then
	echo "	curl -Lo ${WRAP_source_filename} ${WRAP_source_url}"
	if [ -n "${WRAP_source_hash}" ]; then
		echo "	echo Check ${WRAP_source_hash}"
	fi
	echo "	tar xzf ${WRAP_source_filename}"
	echo "	cd ${WRAP_directory}"
else
	if [ -n "${WRAP_depth}" ]; then
		GIT_FLAGS="--depth=${WRAP_depth} "
	fi
	if [ -n "$WRAP_revision" ]; then
		echo "	git clone --no-checkout ${GIT_FLAGS}${WRAP_url} ${WRAP_directory}"
		echo "	cd ${WRAP_directory} && git fetch ${GIT_FLAGS}origin ${WRAP_revision}"
	else
		echo "	git clone ${GIT_FLAGS}${WRAP_url} ${WRAP_directory}"
		echo "	${S}{MAKE} ${WRAP_directory}_all"
	fi
	echo "${NAME}" | grep -q -- '_git'
	if [ $? != 0 ]; then
		echo "	echo Not supported && exit 1"
	fi
	echo "	cd ${WRAP_directory} && git checkout FETCH_HEAD"
fi

if [ -n "$WRAP_patch_directory" ]; then
	echo "	cp -rf packagefiles/${WRAP_patch_directory}/* ${WRAP_directory}"
fi
if [ -n "$WRAP_diff_files" ]; then
	echo "	for a in $(echo "${WRAP_diff_files}" | tr "," " ") ; do echo \"patch -d ${WRAP_directory} -p1 < \$\$a\" ; patch -d ${WRAP_directory} -p1 < \$\$a ; done"
fi

cat <<EOF

${WRAP_name}_clean:
	rm -rf ${WRAP_directory}
EOF

) < $F
