#!/bin/sh


# 这是一个自动更新脚本

appfn=rpxc-arm.latest
appfn0=rpxc-arm
applocal=$1
savedir=/geo/sd
tmpdir=/tmp
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

  # 自动运行脚本是否存在
  if [ ! -f "kpl-checker-rpxc-geo.sh" ];then
    wget http://119.96.169.117:3000/kpl-release/release/kpl-checker-rpxc-geo.sh -O kpl-checker-rpxc.sh
  fi
  chmod +x kpl-checker-rpxc.sh

  search_cnt=`cat /geo/app/gcron.conf |grep -v 'grep' |grep -c kpl-checker-rpxc`
  echo "crontab-rpxc:$search_cnt"
  if [ $search_cnt -eq 0 ]
  then
    echo "0 0/1 * * * * $savedir/kpl-checker-rpxc.sh" >>/geo/app/gcron.conf
    echo "0 0/1 * * * * $savedir/kpl-checker-rpxc.sh 加入到任务"
  fi

  # 删除之前的自动启动
  sed -i '/kpl-gnss.sh/d' /geo/app/start.sh
  sed -i '/kpl-gnss.sh/d' /geo/app/gcron.conf

  # 修改DNS
  sed 's/114.114.114.114/192.168.1.1/g' -i /var/run/ppp/resolv.conf

  search_cnt=`cat /geo/app/start.sh |grep -v 'grep' |grep -c kpl-checker-rpxc`
  echo "start-rpxc:$search_cnt"
  if [ $search_cnt -eq 0 ]
  then
    echo "$savedir/kpl-checker-rpxc.sh &" >>/geo/app/start.sh
    echo "$savedir/kpl-checker-rpxc.sh 启动脚本"
  fi

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

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

  echo "解压文件$tmpdir/$appfn0 到$applocal"
  cp $tmpdir/$appfn0 $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-arm'`
  echo "cnt:$search_cnt"
  if [ $search_cnt -gt 0 ]
  then
    ps |grep 'rpxc-arm' |grep -v 'grep' |grep -v 'sh' |awk '{print $1}'|xargs kill -9
    echo "rpxc-arm killed"
  fi

  ./$applocal -proxysvr=rpx.kplgnss.com:15102 -apptype=GEO -uuidfile=/geo/sd/rpxc.uuid -cmd-addr=:2001 &
fi

