#!/bin/sh

. /lib/functions.sh

IPATH="/tmp/oaf_install"
TMP_FILE="/tmp/oaf.tar.gz"

log()
{
	echo "$1" >>/tmp/log/oaf_install.log
}

install()
{
	local pkg_file=$1
	mkdir $IPATH
	tar -zxvf $pkg_file -C $IPATH  >/dev/null
	if [ $? -ne 0 ];then
		return 2
	fi
	cd $IPATH
	ipk_dir=`ls`
	cd $ipk_dir
	if [ -f install.sh ];then
		cp install.sh /usr/bin/oaf.sh
		chmod 777 /usr/bin/oaf.sh
	fi
	/usr/bin/oaf.sh install 
	if [ $? -ne 0 ];then
		rm $IPATH -fr
		return 1
	else
		rm $IPATH -fr
		return 0
	fi
}
uninstall()
{
	if [ -f /usr/bin/oaf.sh ];then
		/usr/bin/oaf.sh uninstall >/dev/null
	fi
}

upgrade(){
	url=$1
	wget $url -O $TMP_FILE -T 5 >/dev/null
	if [ $? -ne 0 ];then
		echo "40001" >/tmp/oaf_mgr_result
		log "download package failed"
		return
	fi
	log "download package ok"
	uninstall
	install $TMP_FILE
	local ret=$?
	if [ $ret -eq 2 ];then
		echo "40002" >/tmp/oaf_mgr_result
		log "oaf package format error"
		return
	elif [ $ret -eq 1 ];then
		log "install oaf package failed"
		echo "40003" >/tmp/oaf_mgr_result
	
		return
	fi
	log "install oaf ...ok"
	echo "20000" >/tmp/oaf_mgr_result
}
echo "" >/tmp/log/oaf_install.log
action=$1
case $action in
"install")
	log "install"
	install $2
	if [ $? -ne 0 ];then
		return 1
	else
		return 0 
	fi
;;
"uninstall")
	log "uninstall"
	uninstall $2
;;
"upgrade")
	sync
	log "begin upgrade"
	upgrade $2
;;
*)
	echo "error..."
;;
esac

