#!/bin/sh

# 使用说明：
# eg:
#   ./upgrade.sh "0504031838000019" "ftp://ftp.rokid-inc.com/jenkins/platform/images/kamino_rokidos/kamino_yodaos_naboo_gx8010_openai_corp/dev/456"
#   1. naboo ota刷机脚本
#   2. 镜像会下载在脚本当前目录，（而不是你调用的目录）
#   3. 每次执行， 上一次的镜像文件会自动清理
#   4. 注意：脚本离开目录为 脚本当前目
#   5. 你可以在电脑上任何地方调用此脚本，不用担心其中的细节
#  脚本原则：
#       1.  node 调用时, 可能日志信息可能溢出报错。所以减少不必要的信息输出。# command > file 2>&1
#       2.   脚本所在的目录为 originPath
#       3.   所有方法都 cd ${originPath}, 然后开始
#       

#  deviceID="0502031835000171"
#  imageUrl="ftp://ftp.rokid-inc.com/jenkins/platform/images/kamino_rokidos/kamino_yodaos_naboo_gx8010_openai_corp/dev/456"
  deviceID=$1
  imageUrl=$2

getAccount(){
  # 密码 起点为 dirname
  login=`cat ../../config/ftp-account.conf|grep account|awk -F'=' '{print $2}'|awk '{print $1}'`
  password=`cat ../../config/ftp-account.conf|grep password|awk -F'=' '{print $2}'|awk '{print $1}'`
  echo "login" $login
  echo "password" $password
}

init()
{
  echo "===========   init 1    =========="
  ADB="adb -s ${deviceID}"
  cd `dirname $0`
  originPath=`pwd`

  getAccount # 获取账号

  ./checkDeviceOnline.sh ${deviceID}
  if [[ "$?" != 0 ]];then
       echo "${deviceID} not exist, exit  now"
       return 1
  fi

  if [[ ! -d ${deviceID} ]];then
    mkdir ${deviceID}
  fi
  rm -rf ${deviceID}/leo*.zip
	rm -rf ${deviceID}/full_images
}

getImage()
{
  echo "===========downloadImge1=========="
  cd ${originPath} && cd ${deviceID}
  echo "${imageUrl}/*.zip"
	wget ${imageUrl}/*.zip  --ftp-user=${login} --ftp-password=${password} 2> /dev/null 
  # echo $?
  # echo "--ll"
  # return 1
	if [[ "$?" != 0 ]];then
       echo "imageUrl =>" ${imageUrl}
       echo "downloadImge FAILED, exit  now"
       return 1
  fi
  echo "downloadImge success"
}

unzipImageZip()
{
  echo "===========unzipImage=========="
  cd ${originPath} && cd ${deviceID}
	unzip leo*.zip
	if [ "$?" != 0 ];then
       echo "unzipImage FAILED, exit  now"
       return 1
  fi
}

renameImage()
{
  echo "===========rename to ota.img=========="
  cd ${originPath}
	cd ${deviceID}/full_images/
      mv *upgrade.img  ota.img
      if [ "$?" != 0 ];then
        echo "renameImage FAILED, exit  now"
        return 1
      fi
  cd $originPath
}

pushImage()
{
echo "===========push img && js=========="
  cd ${originPath}
	$ADB shell mkdir -p /data/workspace/helper/
	$ADB push upgrade.js /data/workspace/helper/

  cd ${deviceID}/full_images/
	$ADB push ota.img /data/upgrade/ota.img > /dev/null  
	if [ "$?" != 0 ];then
       echo "pushImage FAILED, exit  now"
       return 1
  fi
  cd $originPath
}

rebootImage()
{
  echo "===========image reboot && system reboot=========="
	$ADB shell "iotjs /data/workspace/helper/upgrade.js '/data/upgrade/ota.img'"
	if [ "$?" != 0 ];then
       echo "rebootImage FAILED, exit  now (maybe you should through the USB to brush the devcie )"
       return 1
  fi
  echo "rebootImag end, but it need sometime to be offline, so sleep 10s.."
  sleep 10
}

# checkStart() # del
# {
#    sleep 5
#    while true
#    do
#      let "count--"
#      num=`$ADB get-state |grep host |wc -l`
#      echo "======${num}===="

#     if [[ $[num] == 1 ]]
#       then
#         echo "device started"
#         sleep 5
#         connectWifi
#         return 0
#     elif [[ ${count} == 0 ]]; then
#       echo "=======connect wifi fail========"
#       return 1
#     else
#       sleep 1
#     fi
#    done
# }

checkStartSmart()
{
   count=51  # 100秒倒计时，连接失败说明死机了

   while true
   do
     let "count--"
     echo "--- $count ---"

    ./checkDeviceOnline.sh $1
    if [[ $? == 0 ]];then
        echo "device ${1} started"
        sleep 5
        connectWifi
        if [[ $? != 0 ]];then
          return 1
        fi
        return 0
    elif [[ ${count} == 0 ]]; then
      echo "======= device ${1} can't restart after 100s. status: OFFLINE ========"
      return 1
    else
      sleep 2
    fi
   done
}

connectWifi()
{
  echo "=====mount========"
  $ADB shell mount -o remount,rw /
  echo "=====push wpa_supplicant.conf========"
  $ADB push wpa_supplicant.conf /data/system/
  echo "=====wpa_cli reconfigure========"
  sleep 15
  $ADB shell wpa_cli reconfigure
  if [ "$?" != 0 ];then
         echo "connectWifi, FAILED. exit  now"
         return 1
  fi
  echo "=== connectWifi success ==="
}

init
if [[ "$?" != 0 ]];then
         exit 1
fi

getImage
if [[ "$?" != 0 ]];then
         exit 1
fi
echo "=="
unzipImageZip
if [[ "$?" != 0 ]];then
       exit 1
fi

renameImage
if [[ "$?" != 0 ]];then
       exit 1
fi

pushImage
if [[ "$?" != 0 ]];then
       exit 1
fi

rebootImage
if [[ "$?" != 0 ]];then
       exit 1
fi

# checkStart
checkStartSmart "${deviceID}"
if [[ "$?" != 0 ]];then
    echo " checkStartSmart failed"
    exit 1
fi
echo "sleep 20 ..."
sleep 20
echo "fininsh success"
