#!/bin/sh

if [ $# -gt 1 ]; then
	OUI=$1
	INSTALL_DIR=$2
else
	echo "Usage: $0 <OUI> <INSTALL_DIR>"
	exit 1
fi

UDPI_DIR_NAME="udpi"
UDPI_DIR=$INSTALL_DIR"/"$UDPI_DIR_NAME
UDPI_APP_NAME="m01-us"
UDPI_APP_PATH=$UDPI_DIR"/"$UDPI_APP_NAME
UDPI_TGZ_NAME="udpi.tgz"

udpi_status()
{
	killall -0 $UDPI_APP_NAME > /dev/null 2>&1 
	return $?
}

udpi_start()
{
	$UDPI_APP_PATH &
}

udpi_install()
{
	tar xzf $UDPI_TGZ_NAME
	rm -f $UDPI_TGZ_NAME
}

udpi_download()
{
	local URL=""

	if [ "$OUI" = "miner_x86_64" ]; then
		URL="http://www.freedpi.cn/signature/devops/miner/udpi_x86_64.tgz"
	else
		echo "Now not support $OUI !"
		return 1
	fi

	while true; do
		wget $URL -O $UDPI_TGZ_NAME 2> /dev/null
		if [ $? -eq 0 -a -f $UDPI_TGZ_NAME ]; then
			break
		fi
		sleep 60
	done
    
	return 0
}


udpi_status
if [ $? -eq 0 ] ; then
	echo "$UDPI_APP_NAME is running, do nothing..."
	exit 0
fi

if [ -f $UDPI_APP_PATH ]; then
	udpi_start
	exit 0
fi

cd $INSTALL_DIR

udpi_download
if [ $? -ne 0 ] ; then
	exit 0
fi
udpi_install

udpi_start

exit 0

