#!/bin/bash

#agent版本
version="1.0.6"
#下载域名
host="https://cse-bucket-cn-east-3.obs.cn-east-3.myhuaweicloud.com"
#备份域名
backUpHost=""
#请求路径
path="/javaagent/sermant-agent-"${version}.tar.gz
#实际下载地址
url=
#压缩包名称
name=
#压缩包后缀
suffix=
#解压目标路径
targetPath=~
#目标目录名称
targetName="java-agent"
targetJarName="java-agent.jar"
#解压后的目录名
originFileName="sermant-agent-"$version

init() {
	if [[ "$path" =~ ^/.* ]];then
		path=${path#*/}
	fi
	host=${host#*//}
	backUpHost=${backUpHost#*//}
}

configSuffix() {
	case "$name" in
		*.tar.gz ) suffix=tar.gz;;
		*.tar ) suffix=tar;;
		*.zip ) suffix=zip;;
		* ) echo "Can not recognize suffix of file $name"
			exit 0
		;;
	esac
}

checkHost() {
	ping -c 1 $host > /dev/null
	result=$?
	url=$host/$path
	name=${url##*/}
	configSuffix
	return $result
}

download() {
	wget -O $name $url  -o /dev/null
}

handleAgent() {
	if [ $? -ne 0 ];then
		echo "Can not download $name from $host/$path"
		exit 0
	fi
	if [ -f $name ];then
		if [ "${suffix}" == "tar.gz" ];then
			tar -zxf $name -C $targetPath
		elif [ "${suffix}" == "tar.gz" ];then
			tar -xf $name -C $targetPath
		elif [ "${suffix}" == "zip" ];then
			unzip -q $name -d $targetPath
		fi
		mv $targetPath/$originFileName/agent $targetPath/$targetName
		echo "Success to install java agent at path [${targetPath}/${targetName}]"
		rm -rf $targetPath/$originFileName
		if [ "${targetJarName}" != "sermant-agent.jar" ];then
			mv $targetPath/$targetName/sermant-agent.jar $targetPath/$targetName/$targetJarName 
		fi
	fi
	rm -rf $name
}

process() {
	if [ -n "$1" ];then
		host=$1
	fi
	checkHost
	if [ $? -eq 0 ];then
		download
		handleAgent
		exit 0
	fi
}
init
process $host
if [ -n "$backUpHost" ];then
	process $backUpHost
fi
