#!/bin/sh


# 这是一个自动更新脚本

appfn=rpxc-mips.latest
applocal=$1
savedir=/home
tmpdir=/tmp/rpxc
mkdir -p $savedir
mkdir -p $tmpdir

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


echo "p0:$0"
echo "applocal:$applocal"

cd $tmpdir

rm -rf $appfn.tar.gz
wget "http://119.96.169.117:3000/kpl-release/release/$appfn.tar.gz"

# 比较MD5
rm -rf $appfn.md5
wget "http://119.96.169.117:3000/kpl-release/release/$appfn.md5"

localMD5=`md5sum $appfn.tar.gz |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.tar.gz" ];then
  echo "解压文件$appfn.tar.gz"
  tar -xvzf $appfn.tar.gz -C ./

  cd $savedir

  # 沿用之前的rpxc.uuid文件
  if [ ! -f "rpxc.uuid" ];then
    cp /home/mgr/app.uuid rpxc.uuid
  fi

  # 自动运行脚本是否存在
  wget http://119.96.169.117:3000/kpl-release/release/kpl-gnss.sh -O kpl-gnss.sh
  chmod +x kpl-gnss.sh

  search_cnt=`crontab -l |grep -v 'grep' |grep -c kpl-gnss`
  echo "crontab-rpxc:$search_cnt"
  if [ $search_cnt -eq 0 ]
  then
    echo "*/1 * * * * $savedir/kpl-gnss.sh" >>/etc/crontabs/root
    echo "*/1 * * * * $savedir/kpl-gnss.sh 加入到任务"
  fi

  if [ ! -f "$tmpdir/$appfn" ];then
    echo "$tmpdir/$appfn 不存在!"
    exit 1
  fi

  echo 'md5 verify succ!'
  rm -rf $applocal

  echo "解压文件$tmpdir/$appfn 到$applocal"
  cp $tmpdir/$appfn $applocal
  chmod +x $applocal

  if [ ! -f "$applocal" ];then
    echo "$applocal 不存在!"
    exit 1
  fi
  
  search_cnt=`ps |grep -v 'grep' |grep -v 'sh' |grep -c $applocal`
  echo "cnt:$search_cnt"
  if [ $search_cnt -gt 0 ]
  then  
    ps |grep $applocal |grep -v 'grep' |grep -v 'sh' |awk '{print $1}'|xargs kill -9
    echo "$applocal killed"
  fi

    search_cnt=`ps |grep -v 'grep' |grep -v 'sh' |grep -c 'rpxc-'`
    echo "cnt:$search_cnt"
    if [ $search_cnt -gt 0 ]
    then
      ps |grep "rpxc-" |grep -v 'grep' |grep -v 'sh' |awk '{print $1}'|xargs kill -9
      echo "rpxc- killed"
    fi

  /home/$applocal -proxysvr=rpx.kplgnss.com:15102 -apptype=JSJ -uuidfile=/home/rpxc.uuid &
fi

