#!/bin/bash



# 这是一个自动更新脚本

appfn=gnss-app-linux-arm-x86.latest
applocal=$1
cmdaddr=$2
configfile=$3
isbeta=$4
runflag=$5
url="http://119.96.169.117:3000/kpl-release/release"

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

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

if [ "$cmdaddr"x == ""x ]; then
   cmdaddr=:3000
fi

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

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

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

rm -rf $appfn

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

rm -rf $appfn.tar.gz.md5
wget "$url/$appfn.tar.gz.md5"

sleep 2s
rm -rf $appfn.tar.gz
rm -rf $appfn
wget "$url/$appfn.tar.gz"
sleep 1s

localMD5=`md5sum $appfn.tar.gz |awk 'NR==1'|awk '{print $1}'`
mustMD5=`cat $appfn.tar.gz.md5 |awk '{print $1}'`
echo " local: $localMD5"
echo "expect: $mustMD5"
if [ "$localMD5"x != "$mustMD5"x ]; then
  echo 'md5 verify fail!'
elif [ -f "$appfn.tar.gz" ];then
  echo '解压文件$appfn.tar.gz'
  tar -xvzf $appfn.tar.gz -C ./

  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
    ./$applocal -cmd-addr=$cmdaddr -config-file=$configfile -uuidfile=app.uuid &
  fi
fi

