#!/bin/bash


if [[ ! $(id -u) -eq 0 ]]
then
        echo "Please run as root"
		exit 1
fi


#check memroy /cpu info - recommend 4 cpu 8GB mem or higher
_check_hw_req()
{
	tmem=`free -m|grep Mem|awk '{ print $2 }'`
	#echo "Mem $tmem"
	if [ $tmem -lt 6000 ]; then
		echo -e "\e[31m内存容量为${tmem}MB，控制中心可能运行缓慢或错误。请配置控制中心主机至少8GB内存\e[0m"
		exit 8
	fi
	tcpu=`lscpu|grep -E '^CPU:\s*[0-9]{1,}|^CPU\(s\):\s*[0-9]{1,}'|awk '{ print $2 }'`
	#echo "CPU $tcpu"
	if [ $tcpu -lt 2 ]; then
		echo -e "\e[33mCPU个数$tcpu，控制中心可能会运行缓慢或出错。建议4CPU或更多\e[0m"
	elif [ $tcpu -lt 4 ]; then
		echo -e "\e[33mCPU个数$tcpu，控制中心可能会运行缓慢。建议4CPU或更多\e[0m"
	fi
	# min disk free space 20G
	freespace=`df -BG / --output='avail'|grep -Eo "[0-9]{1,}"`
	if [ $freespace -lt 25 ];then
		echo -e "\n\e[33m/ 剩余空间${freespace}GB，控制中心安装和运行可能会出错。建议 / 剩余空间25GB或以上\e[0m\n"
	fi
}
_check_hw_req

_check_file(){
    ff=$1
    echo "Checking $ff..."
    curmd5=`md5sum $ff|awk '{ print $1 }'`
    rmd5=$(head -n1 ${ff}.md5|awk '{ print $1 }')
    if [ "$curmd5" != "$rmd5" ];then
        echo -e "\e[31m$ff 文件损坏，请重新下载\e[0m"
        echo -e "\e[31m$ff is corrupted, please download again\e[0m"
        echo -e  "\e[31mmd5: $curmd5 expected: $rmd5 \e[0m"
        exit 2
    fi
}

#check data integrity
CUID="esofficial"
if [ ! -f "versions" ];then
    echo -e "\e[31mversions file not exist\e[0m"
    exit 6
fi
bldver=$(head -n1 versions)
ss=$(echo $bldver|grep -oE "[0-9]{4,}\-[a-zA-Z]{2,}"|cut -d '-' -f2)
if [ -n "$ss" ];then #has addon
    CUID=$ss
    faddon=easync-addon-${bldver}.tgz
    if [ ! -f "$faddon" ];then
        echo -e "\e[31mversions: $bldver. ${faddon} is expected but it does not exist\e[0m"
        exit 5
    fi
else #no addon
    echo standard
fi

chmod +x easync-standalone-installer.sh
./easync-standalone-installer.sh $@ -e $CUID

exit 0
