#!/bin/sh

# 使用说明：
# eg:
#   - naboo
#     ./upgrade.sh "0504031838000019" "ftp://ftp.rokid-inc.com/jenkins/platform/images/kamino_rokidos/kamino_yodaos_naboo_gx8010_openai_corp/dev/456"
#   - YodaOS Rokid-mini
#     ./upgrade.sh "0302041802000496" "ftp://ftp.rokid-inc.com/jenkins/platform/images/YodaOS_A113/YodaOS_A113_Mini/dev/214/"
#   1. YodaOS Rokid-mini  && 兼容 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/568"



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}
}

# 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    =========="
  ADB="adb -s ${deviceID}"
  echo `dirname $0`
  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}/*.zip # modify
	rm -rf ${deviceID}/full_images


}

getImage()
{
  echo "===========downloadImge1=========="
  cd ${originPath} && cd ${deviceID}
  echo "${imageUrl}/*.zip"
	wget ${imageUrl}/*.zip  --ftp-user=${ftpAccount} --ftp-password=${ftpPassword} 2> /dev/null  # import
  # 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 *.zip # modify
	if [ "$?" != 0 ];then
       echo "unzipImage FAILED, exit  now"
       return 1
  fi
}

renameImage()
{
  echo "===========rename to ota.img=========="
  cd ${originPath}
	cd ${deviceID}/full_images/
      mv *ota.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/ # del
	# $ADB push upgrade.js /data/workspace/helper/ # del

  echo "[warning] 确保设备有 deviceID ， deviceTypeID(不正确无法配网), 不在工厂模式(工厂模式reboot没有反应会一直等待)."

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

rebootImage()
{
  echo "===========image reboot && system reboot=========="
	# $ADB shell "iotjs /data/workspace/helper/upgrade.js '/data/upgrade/ota.img'"
  $ADB shell unpack_cli set
  $ADB shell reboot # 确保设备有 deviceID ， deviceTypeID, 不在工厂模式(工厂模式reboot没有反应会一直等待).
	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=81  # 160秒倒计时，连接失败说明死机了

   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
}

delImage()
{
  $ADB shell rm -f /data/ota_upgrade.img
  if [[ "$?" != 0 ]];then
      echo "删除 /data/ota_upgrade.img 失败， EXIT"
      return 1
  fi
}

generateWifiConfig()
{
cd ${originPath} && pwd
content="ctrl_interface=DIR=/var/run/wpa_supplicant
update_config=1

network={
        ssid=\"${wifiAccount}\"
        scan_ssid=1
        psk=\"${wifiPassword}\"
}"

printf "${content}" > wpa_supplicant.conf
}

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 ==="
}


readConfig $@

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

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

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

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 2 # important
fi

 


sleep 5
connectWifi
if [[ $? != 0 ]];then
    exit 1 
fi

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

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