#!/bin/sh

. ../common/ajax_common

APPROOT="${RAMDISK}/app"
APPUPDIR="${RAMDISK}/appupgrade"
APPIMGDIR="${RAMDISK}/admin/app_img"

curdir=`pwd`
BSDVER=`uname -r | cut -d'-' -f1`
SVRIP="download.panabit.com"
SVRURL="https://${SVRIP}:9443"
CURL="${CURL} -k --connect-timeout 20"


if [ "${PALANG}" = "en" ]; then
	LANG001="Error"				#ʧ
	LANG002="Success"			#ɹ
	LANG003="Install Success"	#װɹ
fi


resolv_cloud_ip()
{
	SVRIP=`${FLOWEYE} nslookup download.panabit.com 114.114.114.114`

	[ $? -ne 0 ] && return 1

	SVRURL="https://${SVRIP}:9443"

	return 0
}


list_local_app()
{
	dot=""

    [ ! -d ${APPIMGDIR} ] && mkdir -p ${APPIMGDIR}

	# cits: 347
	if [ "${PANABIT_USER}" = "wbadmin" ]; then
		printf "[]"
		return 
	fi

	printf "["

	for app in `ls ${APPROOT}`
	do
		appinf="${APPROOT}/${app}/app.inf"
		appctrl="${APPROOT}/${app}/appctrl"
		app_cname_en=""
		app_desc_en=""
		app_onmenu=0
		system_app=0
		app_tag=""

		[ ! -e ${appinf} ] && continue
		[ ! -x ${appctrl} ] && continue

		syntax=`sh -n ${appctrl} 2>&1`
		[ $? -ne 0 ] && continue

		. ${appinf}
		[ "${system_app}" = "1" ] && continue
		[ "${app_width}" = "" ] && app_width=600
		[ "${app_height}" = "" ] && app_height=400

		app_status=`${appctrl} status`
		app_icon="${APPROOT}/${app}/app.png"

        if [ -e ${app_icon} ]; then
            cp ${app_icon} ${APPIMGDIR}/${app}.png
            app_icon="/app_img/${app}.png"
        else
            app_icon="/img/PAlogo.png"
        fi
		
		if [ "${PALANG}" = "en" ]; then
			app_cname=${app_cname_en}
			app_desc=${app_desc_en}
			[ "${app_cname}" = "" ] && app_cname=${app_name}
			[ "${app_desc}" = "" ] && app_desc=${app_name}
		fi

		printf "${dot}{"
		printf "\"app_id\":\"${app_id}\","
		printf "\"app_name\":\"${app_name}\","
		printf "\"app_cname\":\"${app_cname}\","
		printf "\"app_desc\":\"${app_desc}\","
		printf "\"app_width\":\"${app_width}\","
		printf "\"app_height\":\"${app_height}\","
		printf "\"app_status\":\"${app_status}\","
		printf "\"app_version\":\"${app_version}\","
		printf "\"app_onmenu\":\"${app_onmenu}\","
		printf "\"app_tag\":\"${app_tag}\","
		printf "\"app_times\":0,"
		printf "\"app_icon\":\"${app_icon}\""
		printf "}"

		[ "${dot}" = "" ] && dot=","
	done

	printf "]" 
}


fetch_cloud_app()
{
	resolv_cloud_ip

	[ $? -ne 0 ] && return

	url="${SVRURL}/api/panabit_app_list.json"

	if [ "`uname`" = "Linux" ]; then
		${CURL} ${url} -o ${curdir}/public.text >/dev/null 2>&1 
	else
		${CURL} ${url} -o ${curdir}/public.text >/dev/null 2>&1 
	fi
}


list_cloud_app()
{
	cloudapp="[]"

	fetch_cloud_app

	if [ -f ${curdir}/public.text ]; then
		cloudapp=`cat ${curdir}/public.text`
		[ "${cloudapp}" = "" ] && cloudapp="[]"
	fi

	echo -n "${cloudapp}"
}


list_all_app()
{
	echo -n "{"
	echo -n "\"local\":`list_local_app`,"
	echo -n "\"cloud\":`list_cloud_app`"
	echo -n "}"
}


delete_app()
{
	[ "${CGI_app}" = "" ] && retjson 1 "NO_APP_FIND"

	apppath="${PGPATH}/app/${CGI_app}"
	[ ! -d ${apppath} ] && retjson 1 "NO_APP_FIND"

	[ ! -e ${apppath}/app.inf ] && retjson 1 "NO_APP_FIND"

	if [ -x ${apppath}/preuninstall ]; then
		errmsg=`${apppath}/preuninstall`
		[ "$?" != "0" ] && retjson 1 "${errmsg}"
	fi

	errmsg=`${apppath}/appctrl stop`
	sleep 1
	[ -x ${apppath}/afteruninstall ] && errmsg=`${apppath}/afteruninstall`
	rm -rf /usr/ramdisk/app/${CGI_app}
	rm -rf ${apppath}

	[ -d /usr/ramdisk/admin/cgi-bin/App/${CGI_app} ] && rm -rf /usr/ramdisk/admin/cgi-bin/App/${CGI_app}
	[ -d /usr/ramdisk/admin/html/App/${CGI_app} ] && rm -rf /usr/ramdisk/admin/html/App/${CGI_app}
	[ -d /usr/ramdisk/admin/App/${CGI_app} ] && rm -rf /usr/ramdisk/admin/App/${CGI_app}

	WEB_LOGGER "ɾAPP" "name=${CGI_app}"
	retjson 0 "${LANG002:=ɹ}"
}


disable_app()
{
	appctrl="${APPROOT}/${CGI_app}/appctrl"
	[ ! -e ${appctrl} ] && retjson 1 "NO_APP_FIND"

	errmsg=`${appctrl} disable`

	if [ "$?" != "0" ]; then
		errlist=`awk '{printf ",\"%s\"", $0}' <<EOF
${errmsg}
EOF
`
		retjson 1 "ʧ" "[\"\" ${errlist}]"
	fi

	WEB_LOGGER "APP" "name=${CGI_app}"
	retjson 0 "${LANG002:=ɹ}"
}


enable_app()
{
	appctrl="${APPROOT}/${CGI_app}/appctrl"
	[ ! -e ${appctrl} ] && retjson "1" "NO_APP_FIND"

	errmsg=`${appctrl} enable`

	if [ "$?" != "0" ]; then
		errlist=`awk '{printf ",\"%s\"", $0}' <<EOF
${errmsg}
EOF
`
		retjson 1 "ʧ" "[\"\" ${errlist}]"
	fi

	WEB_LOGGER "APP" "name=${CGI_app}"
	retjson 0 "${LANG002:=ɹ}"
}


install_app()
{
	local app_installroot="${1}"

	#app.inf, appctrl
	appctrl=`find ${app_installroot} -name appctrl`

	if [ "${appctrl}" = "" ]; then
		rm -rf ${app_installroot}
		retjson 1 "װûappctrlűֹװ!"
	fi

	if [ ! -x ${appctrl} ]; then
		rm -rf ${app_installroot}
		retjson 1 "appctrlűǿִгֹװ!"
	fi

	appinf="`dirname ${appctrl}`/app.inf"
	if [ ! -e ${appinf} ]; then
		rm -rf ${app_installroot}
		retjson 1 "һЧAPPװ"  "[\"ȱҪļ:app.inf\"]"
	fi

	. ${appinf}

	if [ "${app_name}" = "" -o "${app_id}" = "" -o "${app_cname}" = "" ]; then
		rm -rf ${app_installroot}
		retjson 1 "ЧAPPƻIDֹװ!"
	fi

	preinstall="${app_installroot}/preinstall"
	if [ -x ${preinstall} ]; then
		errmsg=`${preinstall}`
		if [ "$?" != "0" ]; then
			rm -rf ${app_installroot}
			retjson 1 "װ${app_cname}" "[\"${errmsg}\"]"
		fi

		rm -f ${preinstall}
	fi

	mkdir -p ${PGPATH}/app/${app_name}
	mkdir -p ${RAMDISK}/app/${app_name}
	cp -Rf ${app_installroot}/* ${PGPATH}/app/${app_name}/
	rm -rf ${app_installroot}/*
	cp -Rf ${PGPATH}/app/${app_name}/* ${RAMDISK}/app/${app_name}/
	sync

	afterinstall="${RAMDISK}/app/${app_name}/afterinstall"
	if [ -x ${afterinstall} ]; then
		errmsg=`${afterinstall}`
		rm -f ${PGPATH}/app/${app_name}/afterinstall
		rm -f ${RAMDISK}/app/${app_name}/afterinstall
	fi

	appctrl="${RAMDISK}/app/${app_name}/appctrl"
	errmsg=`${appctrl} start`

	if [ "$?" != "0" ]; then
		errlist=`awk '{printf ",\"%s\"", $0}' <<EOF
${errmsg}
EOF
`
		retjson 2 "${app_cname}װɹʧ" "[\"\" ${errlist}]"
	fi

	sync
}


upload_app()
{
	# verify the ramdisk size
	ram_size=10000
	ram_size=`df -k | awk '{if($6=="/usr/ramdisk")print $4}'`

	if [ ${ram_size} -le 7000 ]; then
		rm -rf "${CGI_file}"
		retjson 1 "RAMDISKĿ¼ռС7M<br>${cname}ֹͣװ"
	fi

	local app_installroot="${APPUPDIR}/__tmp__"

	# give it more space for upgrading
	[ -d ${app_installroot} ] && rm -rf ${app_installroot}
	mkdir -p ${app_installroot}  

	# verify the archive
	if [ "`tar ztf ${CGI_file} | grep app.inf`" = "" ]; then
		rm -rf ${CGI_file}
        retjson 1 "ϴļһЧAPPװ"
	fi

	errmsg=`tar xzf ${CGI_file} -C ${app_installroot} 2>&1`

	if [ "$?" != "0" ]; then
		rm -rf ${app_installroot}
		rm -rf ${CGI_file}
        sync
        retjson 1 "װ޷⿪!"
	fi

	rm -rf ${CGI_file}
	sync

	appinf=`find ${app_installroot} -name "app.inf" -maxdepth 1`

	[ "${appinf}" = "" ] && retjson 1 "ϴļһЧAPPװ"

	data=`awk -F "=" \
	'BEGIN{
		dot = "";
		printf "{";
	}{
		gsub("\"", "", $2);

		printf "%s", dot;
		printf "\"%s\":\"%s\"", $1, $2;
		if(dot == "") dot = ",";
	}END{
		printf "}";
	}' ${appinf} `

	retjson 0 "ϴɹ" "${data}"
}


confirm_install_app()
{
	local app_installroot="${APPUPDIR}/__tmp__"

	install_app "${app_installroot}"

	WEB_LOGGER "ֶװAPP" "appname=${CGI_app_cname}"
	retjson 0 "${LANG002:=ɹ}"
}


cancel_install_app()
{
	local app_installroot="${APPUPDIR}/__tmp__"
	[ -d ${app_installroot} ] && rm -rf ${app_installroot}
	
	retjson 0 "OK"
}


auto_install_app()
{
	[ "${CGI_app_name}" = "" ] && retjson 1 "NO_APP_NAME"
	[ "${CGI_file_md5}" = "" ] && retjson 1 "NO_FILE_MD5"

	curdir=`pwd`

	resolv_cloud_ip
	
	[ $? -ne 0 ] && retjson 1 "ʧ"

    filename="PanabitApp_${CGI_app_name}.apx"
    filepath="${curdir}/${filename}"

    url="${SVRURL}/json/index.php?r=package&action=download_package&file_md5=${CGI_file_md5}"
	local app_installroot="${APPUPDIR}/${CGI_app_name}"

	# verify the ramdisk size
	ram_size=10000
	ram_size=`df -k | awk '{if($6=="/usr/ramdisk")print $4}'`
	[ ${ram_size} -le 7000 ] && retjson 1 "RAMDISKĿ¼ռС7M<br>${CGI_app_cname}ֹͣװ"

	# download file
    if [ ${linux} -eq 1 ]; then
    	${CURL} ${url} -o ${filepath} >/dev/null 2>&1
    else
        ${CURL} ${url} -o ${filepath} >/dev/null 2>&1
    fi

    [ ! -f ${filepath} ] && retjson 1 "${CGI_app_cname}ʧ!"

	# give it more space for upgrading
	[ -d ${app_installroot} ] && rm -rf ${app_installroot}
	mkdir -p ${app_installroot}  

	# verify the archive
	if [ "`tar ztf ${filepath} | grep app.inf`" = "" ]; then
		rm -rf ${filepath}
        retjson 1 "ص${CGI_app_cname}һЧAPPװ!"
	fi

	errmsg=`tar xzf ${filepath} -C ${app_installroot} 2>&1`
	if [ "$?" != "0" ]; then
		rm -rf ${app_installroot}
		rm -rf ${filepath}
        sync
        retjson 1 "${CGI_app_cname}İװ޷⿪!"
	fi
	rm -rf ${filepath}
	sync

	install_app ${app_installroot}

	WEB_LOGGER "Ӧ̵갲װAPP" "name=${CGI_app_cname}"
	retjson 0 "${CGI_app_cname} ${LANG:=װɹ}"
}


case "${CGI_action}" in
	"_list_local_app_")
		list_local_app
		;;

	"list_local_app")
		retjson 0 "OK" "`list_local_app`"
		;;

	"list_cloud_app")
		retjson 0 "OK" "`list_cloud_app`"
		;;

	"list_all_app")
		retjson 0 "OK" "`list_all_app`"
		;;

	"fetch_cloud_app")
		action_check
		fetch_cloud_app
		;;

	"delete_app")
		action_check
		delete_app
		;;

	"disable_app")
		action_check
		disable_app
		;;

	"enable_app")
		action_check
		enable_app
		;;

	"upload_app")
		action_check
		upload_app
		;;

	"confirm_install_app")
		action_check
		confirm_install_app
		;;

	"cancel_install_app")
		action_check
		cancel_install_app
		;;

	"auto_install_app")
		action_check
		auto_install_app
		;;

	"shell_install_app")
		# е
		install_app "${1}"
		;;

	*)
		retjson 1 "UNKNOW_ACTION!"
		;;
esac
