#!/bin/bash



# 这是一个自动更新脚本
# $4 1:会过期, 0: 不过期
# $6 指定版本, 或者beta

appfn0=gnss-app-linux-amd64
appfn=$appfn0.latest
applocal=$1
cmdaddr=$2
configfile=$3
isbeta=$4
runflag=$5
ver=$6
url="http://119.96.169.117:3006/gnss/release"


if [ "$runflag"x == ""x ]; then
   runflag=1
fi

if [ "$applocal"x == ""x ]; then
   applocal=kpl-app
   runflag=0
fi

if [ "$isbeta"x == ""x ]; then
   isbeta=1
fi

if [ "$cmdaddr"x == ""x ]; then
   cmdaddr=:6107
   runflag=0
fi

if [ "$configfile"x == ""x ]; then
   configfile=plugs-conf.json
   runflag=0
fi



echo "p0:$0"
echo "applocal:$applocal"
echo "cmdaddr:$cmdaddr"
echo "configfile:$configfile"
echo "isbeta:$isbeta"
echo "ver:$ver"

rm -rf $appfn

if [ "$isbeta"x == "1"x ]; then
  url="http://119.96.169.117:3006/gnss/tools"
fi

appurl=$url/$appfn
md5url=$url/$appfn.md5

if [ "$ver"x == "beta"x ]; then
  appurl=$url/$appfn0.beta
  md5url=$url/$appfn0.beta.md5
elif [ "$ver"x != ""x ]; then
  appurl=$url/daily/$appfn0.$ver
  md5url=$url/daily/$appfn0.$ver.md5
fi

echo "url:$appurl"
wget "$appurl" -O $appfn


# 比较MD5
rm -rf $appfn.md5
wget "$md5url" -O $appfn.md5

localMD5=`md5sum $appfn |awk 'NR==1'|awk '{print $1}'`
mustMD5=`cat $appfn.md5 |awk '{print $1}'`
echo " local: $localMD5"
echo "expect: $mustMD5"
if [ "$localMD5"x != "$mustMD5"x ]; then
  echo 'md5 verify fail!'
elif [ -f "$appfn" ];then
  echo 'md5 verify succ!'
  rm -rf $applocal
  cp $appfn $applocal
  chmod +x $applocal

  search_cnt=`ps -ef|grep -v 'grep' |grep -v 'sh' |grep -v 'rpxc-' |grep -c $applocal`
  echo "cnt:$search_cnt"
  if [ $search_cnt -gt 0 ]
  then
    ps -ef|grep $applocal |grep -v 'grep' |grep -v 'sh' |grep -v 'rpxc-' |awk '{print $2}'|xargs kill -9
    echo "$applocal killed"
  fi
  if [ "$runflag"x == "1"x ]; then
    if [ "$cmdaddr"x == ":"x ]; then
      ./$applocal -config-file=$configfile -uuidfile=app.uuid &
    else
      ./$applocal -cmd-addr=$cmdaddr -config-file=$configfile -uuidfile=app.uuid &
    fi
  fi
fi

