#!/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="http://ci-s.rokid-inc.com/job/os_android_image_develop/lastSuccessfulBuild/artifact/out/target/product/msm8998/msm8998-ota-eng.jenkins.zip"


readConfig(){
help="Usage:
--deviceID <设备sn号> --imageUrl <镜像地址> 
--ftpAccount <ftp账号> --ftpPassword <ftp密码> 
--wifiAccount <wifi账号> --wifiPassword <wifi密码>
"

deviceID=""
imageUrl=""
ftpAccount=""
ftpPassword=""
  while [ $# -gt 0 ]; do
    case "$1" in
      --deviceID)
        deviceID="$2"
        shift
        ;;
      --imageUrl)
        imageUrl="$2"
        shift
        ;;
      --ftpAccount)
        ftpAccount="$2"
        ;;
      --ftpPassword)
        ftpPassword="$2"
        shift
        ;;
      --wifiAccount)
        wifiAccount="$2"
        ;;
      --wifiPassword)
        wifiPassword="$2"
        shift
        ;;
      --help)
        printf "$help"
        exit
        ;;
      -h)
        printf "$help"
        exit
        ;;
      --*)
        echo "Illegal option $1"
        ;;
    esac
    shift $(( $# > 0 ? 1 : 0 ))
  done

if test "$deviceID" = ""; then
  printf "deviceID 为空"
  exit 1
fi
if test "$imageUrl" = ""; then
  printf "imageUrl 为空"
  exit 1
fi
if test "$ftpAccount" = ""; then
  printf "ftpAccount 为空"
  exit 1
fi
if test "$ftpPassword" = ""; then
  printf "ftpPassword 为空"
  exit 1
fi
if test "$wifiAccount" = ""; then
  printf "ftpAccount 为空"
  exit 1
fi
if test "$wifiPassword" = ""; then
  printf "ftpPassword 为空"
  exit 1
fi

echo "deviceID" ${deviceID}
echo "imageUrl"  ${imageUrl}
echo "ftpAccount" ${ftpAccount}
echo "ftpPassword" ${ftpPassword}
echo "wifiAccount" ${wifiAccount}
echo "wifiPassword" ${wifiPassword}
}

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

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

  rm -rf ${deviceID}
  mkdir ${deviceID}
}

getImage()
{
  ## 通过wget到ci获取ota镜像
  echo "===========downloadImg=========="
  cd ${originPath} && cd ${deviceID}
  echo "${imageUrl}"
	wget ${imageUrl} 2> /dev/null 
	if [[ "$?" != 0 ]];then
       echo "imageUrl =>" ${imageUrl}
       echo "downloadImge FAILED, exit  now"
       return 1
  fi
  echo "downloadImge success"
}

renameImage()
{
  ## 将镜像重新命名为update.zip
  echo "===========rename to update.zip=========="
  cd ${originPath}
	cd ${deviceID}
  mv *.zip update.zip
  if [ "$?" != 0 ];then
    echo "renameImage FAILED, exit  now"
    return 1
  fi
  cd $originPath
}

updateImage()
{
  echo "===========push update.zip to sdcard=========="
  cd ${originPath}
  cd ${deviceID}
    $ADB root
    $ADB remount
	$ADB push update.zip /sdcard/update.zip > /dev/null
	if [ "$?" != 0 ];then
       echo "pushImage FAILED, exit  now"
       return 1
  fi
  ## 发送广播强制ota升级
  $ADB shell am broadcast -a android.intent.customize.action.JUDGE_BEFORE_UPDATE
  if [ "$?" != 0 ];then
       echo "update ota FAILED, exit  now"
       return 1
  fi
  cd $originPath
  echo "sleep 120 for ota update"
  sleep 120
}

rebootImage()
{
  echo "===========image reboot && system reboot=========="
	$ADB reboot
	if [ "$?" != 0 ];then
       echo "rebootImage FAILED, exit  now (maybe you should through the USB to brush the devcie )"
       return 2
  fi
  echo "rebootImag end, but it need sometime to be offline, so sleep 10s.."
  sleep 10
}

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

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

readConfig $@

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

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

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

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

## TODO 检查ota完成！！！

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

# checkStart
checkStartSmart "${deviceID}"
if [[ "$?" != 0 ]];then
    echo " checkStartSmart failed"
    exit 2 # important
fi
$ADB root

echo "sleep 20 ..."
sleep 20
echo "fininsh success"
