#!/bin/bash
crawler_dir=$1  # 爬虫执行路径，如: ./youtube/youtube_main/run_youtube_follow.py
log_type=$2     # 日志命名格式，如: follow，则在 youtube/logs/目录下，生成 2023-02-08-follow.log
crawler=$3      # 哪款爬虫，如: youtube / kanyikan / weixinzhishu
env=$4          # 爬虫运行环境，正式环境: prod / 测试环境: dev
#nohup_dir=$5    # nohup日志存储路径，如: ./youtube/nohup.log

if [ ${env} = "--env=prod" ];then
  piaoquan_crawler_dir=/Users/piaoquan/Desktop/piaoquan_crawler/
  profile_path=/etc/profile
  python=/usr/bin/python3
  node_path=/usr/local/bin/node
  nohup_log_path=${piaoquan_crawler_dir}shipinhao/logs/$(date +%Y-%m-%d)-run-shell.log
elif [ ${env} = "--env=dev" ];then
  piaoquan_crawler_dir=/Users/wangkun/Desktop/crawler/piaoquan_crawler/
  profile_path=/etc/profile
  node_path=/opt/homebrew/bin/node
  python=python3
  nohup_log_path=${piaoquan_crawler_dir}shipinhao/logs/$(date +%Y-%m-%d)-run-shell.log
fi

#rm -f ${piaoquan_crawler_dir}shipinhao/logs/appium.log
#ps aux | grep shipinhao_search | grep -v grep | awk '{print $2}' | xargs kill -9

echo "开始..." >> ${nohup_log_path}
echo "$(date "+%Y-%m-%d %H:%M:%S") 更新环境变量..." >> ${nohup_log_path}
cd ~ && source ${profile_path}
# shellcheck disable=SC2129
echo "$(date "+%Y-%m-%d %H:%M:%S") 更新环境变量完成！" >> ${nohup_log_path}

echo "$(date "+%Y-%m-%d %H:%M:%S") 正在更新代码..." >> ${nohup_log_path}
#cd ${piaoquan_crawler_dir} && git pull origin master --force
echo "$(date "+%Y-%m-%d %H:%M:%S") 代码更新完成！" >> ${nohup_log_path}

echo "$(date "+%Y-%m-%d %H:%M:%S") 正在检测 Appium 运行状态" >> ${nohup_log_path}
  ps aux | grep Appium.app | grep -v grep | awk '{print $2}' | xargs kill -9
  ps -ef | grep "/Applications/Appium.app/Contents/Resources/app/node_modules/appium/build/lib/main.js" | grep -v "grep"
  if [ "$?" -eq 1 ];then
    echo "$(date "+%Y-%m-%d %H:%M:%S") Appium 异常停止,正在重启!" >> ${nohup_log_path}
    nohup ${node_path} /Applications/Appium.app/Contents/Resources/app/node_modules/appium/build/lib/main.js >> ${piaoquan_crawler_dir}shipinhao/logs/appium.log 2>&1 &
    echo "$(date "+%Y-%m-%d %H:%M:%S") 重启Appium完毕!" >> ${nohup_log_path}
  else
#    rm -f ${piaoquan_crawler_dir}shipinhao/logs/appium.log
    echo "$(date "+%Y-%m-%d %H:%M:%S") Appium 运行状态正常" >> ${nohup_log_path}
  fi

echo "$(date "+%Y-%m-%d %H:%M:%S") 正在重启爬虫服务..." >> ${nohup_log_path}
cd ${piaoquan_crawler_dir}
nohup ${python} -u ${crawler_dir} ${log_type} ${crawler} ${env} >> ${nohup_log_path} 2>&1 &
echo "$(date "+%Y-%m-%d %H:%M:%S") 爬虫服务重启完毕!" >> ${nohup_log_path}

exit 0