#!/bin/bash


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


lang_dir="./"
if ls easync-addon-*arcfra.tgz > /dev/null 2>&1; then echo en_US > $lang_dir/lang_script;fi
[ -f $lang_dir/lang_script ] && slang=`cat $lang_dir/lang_script|head -n1|awk '{print $1}'`
lang_file="$lang_dir/${slang:-zh_CN}.lang"
[ -f $lang_file ] && source "$lang_file"

show_msg(){
	echo "$(printf "$@")"
}


#check memroy /cpu info - recommend 4 cpu 8GB mem or higher
_check_hw_req()
{
	echo "Checking memory..."
    tmem=`cat /proc/meminfo|grep MemTotal|awk '{ print $2 }'`
	if [ $tmem -lt 6000000 ]; then
		show_msg "$CC_INSTALL_RAM_LOW" "$tmem"
		exit 8
	fi
    echo "Checking CPU..."
	tcpu=`lscpu|grep -E '^CPU:\s*[0-9]{1,}|^CPU\(s\):\s*[0-9]{1,}'|awk '{ print $2 }'`
	#echo "CPU $tcpu"
	if [ $tcpu -lt 4 ]; then
		show_msg "$CC_INSTALL_CPU_LOW" "$tcpu"
	fi
	# min disk free space 20G
    echo "Checking free space..."
	freespace=`df -BG / --output='avail'|grep -Eo "[0-9]{1,}"`
	if [ $freespace -lt 20 ];then
        show_msg "$CC_INSTALL_DISK_LOW" $freespace
	fi
}
_check_hw_req



predir="$PWD"
cd "$(dirname $0)"

_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 ${CC_INSTALL_FILE_CORRUPTED}\e[0m"
        exit 2
    fi
}

#check data integrity
fbuild=$(ls -r easync-cc-*.tgz 2>/dev/null|head -n1)
if [ -z $fbuild ];then
    echo -e "\e[31mNo build package?\e[0m"
    exit 1
fi
_check_file $fbuild
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
        _check_file $faddon
    else
        echo -e "\e[31mversions: $bldver. ${faddon} is expected but it does not exist\e[0m"
        exit 5
    fi
else #no addon
    echo
fi

chmod +x escc-setup.sh
./escc-setup.sh -yf $fbuild -e $CUID

for fname in "prepare-target" "prepare-target-22.04" "prepare-target.exe" "prepare-target-aarch64"; do
    [ -f $fname ] && chmod +x $fname && \mv -f $fname* /opt/cloudock/easync/cc/download/
done

cd $predir
