#!/bin/sh

if [ ! $1 ]; then
	echo "You must specify a packagename."
	exit 1
fi

VRP_PACKAGE_NAME=$1
VRP_FAKE_ROOT_DIR=/tmp/vrpbuild/${VRP_PACKAGE_NAME}
if [ -d ${VRP_FAKE_ROOT_DIR} ]; then
	echo "Build directory already exists."
	echo "Please check contents and delete ${VRP_FAKE_ROOT_DIR}"
	exit 1
fi

echo "Reading VRP configuration..."
VRP_BUILD_CONF=${VRP_BUILD_CONF:=/opt/snow-gcc-1.4/etc/vrpbuild.conf}
if [ ! -f $VRP_BUILD_CONF ]; then
	echo "No vrpbuild.conf found at $VRP_BUILD_CONF, please create one."
	exit 1
fi
source $VRP_BUILD_CONF

echo "Configuring"
if [ -f ./vrpbuild/vconfig ]; then
	if ! source ./vrpbuild/vconfig; then
		echo "Error configuring $1."
		exit 1
	fi
fi

echo "Building"
if [ -f ./vrpbuild/vbuild ]; then
	if ! source ./vrpbuild/vbuild; then
		echo "Error building $1."
		exit 1
	fi
else
	echo "No build command found, are you sure this is a vrp archive?"
	exit 1
fi

echo "Installing in fake root"
if [ ! -d /tmp/vrpbuild ]; then
	mkdir /tmp/vrpbuild
fi
mkdir ${VRP_FAKE_ROOT_DIR}
if [ -f ./vrpbuild/vinstall ]; then
	if ! source ./vrpbuild/vinstall; then
		echo "Error installing $1."
		rm -f -r ${VRP_FAKE_ROOT_DIR}
		exit 1
	fi
else
	echo "Install command not found, exiting."
	exit 1
fi

echo "Packaging VRP"
vrpcpkg ${VRP_PACKAGE_NAME} ${VRP_FAKE_ROOT_DIR}

echo "Cleaning up"
rm -f -r ${VRP_FAKE_ROOT_DIR}

echo "Done."
