#!/bin/sh


# 这是一个自动更新脚本

appfn=kpl-app-armx86.latest
applocal=$1
cmdaddr=$2
configfile=$3

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

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

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

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

if [ ! -f "/geo/app/kpl/$configfile" ];then
  mkdir -p /geo/app/kpl/
  wget http://119.96.169.117:3000/kpl-release/plug-conf/plugs-robot-geo.json -O /geo/app/kpl/$configfile
fi

if [ ! -f "/geo/app/kpl/$configfile" ];then
  echo "/geo/app/kpl/$configfile not found!!!"
  exit 1
fi

if [ ! -f "/geo/app/kpl/kpl-runner-robot-geo.sh" ];then
  wget http://119.96.169.117:3000/kpl-release/release/kpl-runner-robot-geo.sh -O /geo/app/kpl/kpl-runner-robot-geo.sh
fi

if [ ! -f "/geo/app/kplgettar.sh" ];then
  wget http://119.96.169.117:3000/kpl-release/release/kplgettar.sh -O /geo/app/kplgettar.sh
fi

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


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

localok=0
if [ -f "$appfn.tar.gz" ];then
  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 'localfile md5 verify succ!'
    localok=1
  fi
fi


if [ "$localok"x == "0"x ]; then
  sleep 2s
  rm -rf $appfn.tar.gz
  rm -rf $appfn
  wget -c "http://119.96.169.117:3000/kpl-release/release/$appfn.tar.gz"
  sleep 1s
  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 'md5 verify succ!'
    localok=1
  fi
fi

if [ "$localok"x == "1"x ]; then
  rm -rf $applocal

  echo '解压文件$appfn.tar.gz'
  tar -xvzf $appfn.tar.gz -C /geo/app/kpl/

  echo '解压文件$appfn 到$applocal'
  cd /geo/app/kpl/
  cp $appfn $applocal
  chmod +x $applocal
  
  search_cnt=`ps |grep -v 'grep' |grep -v 'sh' |grep -v 'rpxc-mipsle' |grep -c $applocal`
  echo "cnt:$search_cnt"
  if [ $search_cnt -gt 0 ]
  then  
    ps |grep $applocal |grep -v 'grep' |grep -v 'sh' |grep -v 'rpxc-mipsle' |awk '{print $1}'|xargs kill -9
    echo "`date +"%Y/%m/%d %H:%M:%S"` $applocal killed" >> kplrobot.log
  fi

  ./$applocal -cmd-addr=$cmdaddr -config-file=$configfile -uuidfile=app.uuid &
fi

