#!/bin/sh

. ./ajax_common


query_file()
{
	[ "${CGI_file}" = "" ] && retjson 1 "NO_FILE"

	file_path="${WEB_DOWNLOAD}/${CGI_file}"
	parent_path=`dirname ${file_path}`
	
	[ ! -f "${file_path}" ] && retjson 1 "INV_FILE"
	[ "${parent_path}" != "${WEB_DOWNLOAD}" ] && retjson 1 "INV_FILE"

	[ $1 = "from_web" ] && retjson 0 "OK"
}


download_file()
{
	query_file

	file_path="${WEB_DOWNLOAD}/${CGI_file}"
	file_size=`ls -l ${file_path} | awk '{print $5}'`

	printf "Content-Description: File Transfer\r\n"
	printf "Content-Type: application/octet-stream\r\n"
	printf "Content-Disposition: attachment; filename=${CGI_file}\r\n"
	printf "Content-Transfer-Encoding: binary\r\n"
	printf "Expires: 0\r\n"
	printf "Cache-Control: must-revalidate, post-check=0, pre-check=0\r\n"
	printf "Pragma: public\r\n"
	printf "Content-Length: ${file_size}\r\n"
	printf "\r\n"

	cat ${file_path}
	rm  ${file_path}
}


case "${CGI_action}" in
	"query_file")
		action_check
		query_file "from_web"
		;;

	"download_file")
		action_check
		download_file
		;;

	*)
		retjson 1 "UNKNOW_ACTION"
		;;
esac

