#!/usr/bin/bash

APPTYPE=$1 #cons/app
#constant
APP_IMAGE_NAME=${APP_IMAGE_NAME:-"keyfunc.tencentcloudcr.com/prod/app"}
CONS_IMAGE_NAME=${CONS_IMAGE_NAME:-"keyfunc.tencentcloudcr.com/prod/cons"}
ETL_IMAGE_NAME=${ETL_IMAGE_NAME:-"keyfunc.tencentcloudcr.com/prod/etl"}

DEPLOY_LIST=`kubectl -n epmapp get deploy -l epm-type=$APPTYPE | tail -n+2 | awk '{if($4>0) print $1}'`
echo "system type: ${APPTYPE}, deploy list with pods's num > 0: ${DEPLOY_LIST[@]}"


if [[ $APPTYPE = 'app' ]]; then
    IMAGE_NAME=$APP_IMAGE_NAME 
    ETL_IMAGE_VERSION=$ETL_IMAGE_VERSION
else
    IMAGE_NAME=$CONS_IMAGE_NAME
    ETL_IMAGE_NAME=$CONS_IMAGE_NAME
    ETL_IMAGE_VERSION=$IMAGE_VERSION    
fi

if [ $IMAGE_VERSION ]; then
    echo 'using input image version'
else
  echo 'using lastest image version' 
  #omit surrounding ''
  IMAGE_VERSION=${IMAGE_VERSION:1:-1}    
  ETL_IMAGE_VERSION=${ETL_IMAGE_VERSION:1:-1}
fi

echo "concurrency: $CONCURRENCY,sleep time: $SLEP_TIME, update to web: $IMAGE_NAME:$IMAGE_VERSION,  etl: $ETL_IMAGE_NAME:$ETL_IMAGE_VERSION"

i=0
for deploy in ${DEPLOY_LIST[@]}
do  
  echo "updating $deploy"
  kubectl -n epmapp set image deploy $deploy webservice=$IMAGE_NAME:$IMAGE_VERSION
  if [[ $deploy =~ "-etl" ]]; then
    etl_deploy=$deploy
  else
    etl_deploy="${deploy}-etl"
  fi
  echo "updating $etl_deploy"
  kubectl -n epmapp set image deploy $etl_deploy etlservice=$ETL_IMAGE_NAME:$ETL_IMAGE_VERSION

  i=`expr $i + 1`
  echo $i
  val=`expr $i % $CONCURRENCY`
  if [ $val = 0 ]
  then
        echo "sleep $SLEP_TIME,waiting for pod ready"
        sleep $SLEP_TIME
  fi
done

