#!/bin/bash

array_contains(){
    eval 'local arr=("${'$1'[@]}")'
    local _elem=$2

    for _e in ${arr[@]}
    do
        if [ "$_e" == "$_elem" ]; then
            return 0
        fi
    done
    return 1
}

offline_image_load(){
    local_ip_list=( $(ip -4 a | grep inet | awk -F '[inet|/]' '{print $5}' | xargs) )
    for ip in ${IP_LIST[@]}
    do
        scp Template/appsettings.json root@${ip}:/opt/appsettings.json
        if $(array_contains local_ip_list $ip); then
            docker load -i Install_Packages/Image_*tar
            continue
        fi
        scp $(ls Install_Packages/Image_*tar) root@${ip}:/tmp/
        ssh root@${ip} "docker load -i /tmp/Image_*tar"
        ssh root@${ip} "rm -rf /tmp/Image_*"
    done
}

offline_deploy_mode(){
   offline_image_load
   docker_compose_config
   #pull docker images
   ssh root@${IP_LIST[0]} "docker stack deploy -c ${DOCKER_COMPOSE_DIR}/middleware-master-${MIDDLEWARE_MODE}.yml middleware"
   if [ $? -ne 0 ];then
        echo "ERROR: middleware deploy failed !!!"
        exit 1
   fi
   sleep 20 
   ssh root@${IP_LIST[0]} "cd ${DOCKER_COMPOSE_DIR} && docker stack deploy -c ${DOCKER_COMPOSE_DIR}/${DOCKER_COMPOSE_FILE} indrive"
   if [ $? -ne 0 ];then
         echo "ERROR: ${PRODUCTION} deploy failed !!!"
         exit 1
   fi
  

}

online_deploy_mode(){
   docker_compose_config
   ssh root@${IP_LIST[0]} "docker-compose -f ${DOCKER_COMPOSE_DIR}/middleware-master-${MIDDLEWARE_MODE}.yml pull"
   ssh root@${IP_LIST[0]} "docker stack deploy -c ${DOCKER_COMPOSE_DIR}/middleware-master-${MIDDLEWARE_MODE}.yml middleware"
    if [ $? -ne 0 ];then
        echo "ERROR: middleware deploy failed !!!"
        exit 1
   fi
   #pull docker images
   ssh root@${IP_LIST[0]} "docker-compose -f ${DOCKER_COMPOSE_DIR}/${DOCKER_COMPOSE_FILE} pull" 
   # deploy service
   ssh root@${IP_LIST[0]} "cd ${DOCKER_COMPOSE_DIR} && docker stack deploy -c ${DOCKER_COMPOSE_DIR}/${DOCKER_COMPOSE_FILE} indrive"
     if [ $? -ne 0 ];then
         echo "ERROR: ${PRODUCTION} deploy failed !!!"
         exit 1
   fi
}

deploy_mode(){
    case ${DEPLOY_MODE} in
      offline)
         offline_deploy_mode
         ;;
      online)
         online_deploy_mode
         ;;
      *)
        echo "not supported install method"
        exit 1
    esac
}
