#!/bin/bash


# 这是一个单文件自动更新脚本, 压缩文件不能加路径， 不能带latest[版本信息]
# 会先对比本地版本和服务器的md5是否一致m,如果一致则不会进行更新
# $1 下载的文件
# $2 本地文件名
# $3 1:beta / 0:release
# $4 latest版本或者构建版本

appfn=$1
applocal=$2
isbeta=$3
ver=$4
url="http://119.96.169.117:3006/gnss/release"

TIMEIDSTR=$(date "+%Y%m%d%H%M%S")

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

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


echo "appfn:$appfn"
echo "applocal:$applocal"
echo "isbeta:$isbeta"
echo "ver:$ver"

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

if [ "$ver"x == ""x ]; then
  appurl=$url/$appfn.latest.tar.gz
  md5url=$url/$appfn.latest.md5
elif [ "$ver"x != ""x ]; then
  appurl=$url/daily/$appfn.$ver.tar.gz
  md5url=$url/daily/$appfn.$ver.md5
fi

# 远程MD5
rm -rf $appfn.md5
wget "$md5url" -O $appfn.md5


localok=0
downok=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
    downok=1
  else
    # 备份
    mv $appfn.tar.gz $appfn.tar.gz.bk
  fi
fi

# 本地文件不一致， 进行备份
if [ "$localok"x == "0"x ]; then
  rm -rf $appfn.tar.gz
  rm -rf $appfn.md5
  wget -c "$appurl" -O $appfn.tar.gz
  wget -c "$md5url" -O $appfn.md5
  downret=$?
  if [ "$downret"x == "0"x ]; 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!'
      echo "$TIMEIDSTR download ok:$downret localfile md5 verify succ!" >> up.log
      localok=1
      downok=1
    else
      echo 'localfile md5 verify fail!'
      echo "$TIMEIDSTR download ok:$downret localfile md5 verify fail!" >> up.log
    fi
  else
    TIMEIDSTR=$(date "+%Y%m%d%H%M%S")
    echo "download $TIMEIDSTR faile:$downret" >> up.log
    exit
  fi
fi


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

  echo "解压文件$appfn.tar.gz"
  tar -xvzf $appfn.tar.gz -C ./

  mv $appfn $applocal

  if [ -f "stop.sh" ];then
    ./stop.sh
  fi

fi