#!/bin/sh
paramServerUrl=$1

if [ ! -d "./config/" ];then
  echo "当前不是agent目录，退出更新"
  exit
else
  echo "当前是agent目录，开始更新"
fi

serverUrl=`sed '/^serverUrl=/!d;s/.*=//' ./config/application.properties`
bindIp=`sed '/^bindIp=/!d;s/.*=//' ./config/application.properties`
wgToken=`sed '/^wgToken=/!d;s/.*=//' ./config/application.properties`
submitSeconds=`sed '/^submitSeconds=/!d;s/.*=//' ./config/application.properties`
smartOn=`sed '/^smartOn=/!d;s/.*=//' ./config/application.properties`
logDays=`sed '/^logDays=/!d;s/.*=//' ./config/application.properties`
logCheckSeconds=`sed '/^logCheckSeconds=/!d;s/.*=//' ./config/application.properties`
shellToRun=`sed '/^shellToRun=/!d;s/.*=//' ./config/application.properties`
netInterface=`sed '/^netInterface=/!d;s/.*=//' ./config/application.properties`

#sh stop.sh
currentdate=$(date +%Y%m%d)


echo "开始备份config/application.properties   ->   config/application.properties_$currentdate------"
mv config/application.properties "config/application.properties_$currentdate"
echo "application.properties备份完成------"
echo "开始备份wgcloud-agent-release   ->   wgcloud-agent-release_$currentdate------"
mv wgcloud-agent-release "wgcloud-agent-release_$currentdate"
echo "wgcloud-agent-release备份完成"

echo "开始下载新的application.properties------"
curl -k -o application.properties "${paramServerUrl}/resources/application.properties"
echo "下载完成------"
mv application.properties config/

echo "开始将原来的application.properties值赋值到新的application.properties------"
if [ -n "$serverUrl" ]; then
 sed -i "s#^serverUrl=.*#serverUrl=${serverUrl}#g"  ./config/application.properties
fi
sed -i "s#^bindIp=.*#bindIp=${bindIp}#g"  ./config/application.properties
if [ -n "$wgToken" ]; then
 sed -i "s#^wgToken=.*#wgToken=${wgToken}#g"  ./config/application.properties
fi
if [ -n "$submitSeconds" ]; then
 sed -i "s#^submitSeconds=.*#submitSeconds=${submitSeconds}#g"  ./config/application.properties
fi
if [ -n "$smartOn" ]; then
 sed -i "s#^smartOn=.*#smartOn=${smartOn}#g"  ./config/application.properties
fi
if [ -n "$logDays" ]; then
 sed -i "s#^logDays=.*#logDays=${logDays}#g"  ./config/application.properties
fi
if [ -n "$logCheckSeconds" ]; then
 sed -i "s#^logCheckSeconds=.*#logCheckSeconds=${logCheckSeconds}#g"  ./config/application.properties
fi
if [ -n "$shellToRun" ]; then
 sed -i "s#^shellToRun=.*#shellToRun=${shellToRun}#g"  ./config/application.properties
fi
if [ -n "$netInterface" ]; then
 sed -i "s#^netInterface=.*#netInterface=${netInterface}#g"  ./config/application.properties
fi
echo "赋值完成------"

echo "开始下载新的wgcloud-agent-release------"
curl -k -o wgcloud-agent-release "${paramServerUrl}/resources/wgcloud-agent-release"
echo "下载完成------"

echo "更新完成，开始重启agent------"

if test -x wgcloud-agent-release;
then
echo "准备启动agent------"
else
chmod +x wgcloud-agent-release
fi

sh start.sh
