#!/bin/bash

###
# 集群节点IP地址变更工具 
# 1.编辑"hosts_inventory"文件；
# 2.执行 ./migration.sh
###

set -e

function usage() {
    echo -e "\033[33mUsage:\033[0m migration.sh COMMAND"
    cat <<EOF
-------------------------------------------------------------------------------------
  start            start migrating
  post             restart pod-schedulers after reboot
EOF
}

function logger() {
  TIMESTAMP=$(date +'%Y-%m-%d %H:%M:%S')
  case "$1" in
    debug)
      echo -e "$TIMESTAMP \033[36mDEBUG\033[0m $2"
      ;;
    info)
      echo -e "$TIMESTAMP \033[32mINFO\033[0m $2"
      ;;
    warn)
      echo -e "$TIMESTAMP \033[33mWARN\033[0m $2"
      ;;
    error)
      echo -e "$TIMESTAMP \033[31mERROR\033[0m $2"
      ;;
    *)
      ;;
  esac
}

## 定义主机IP对应关系的文件
FILENAME=hosts_inventory

## 更新集群配置文件中的IP地址信息
function update_ips(){
  # 读取行内容
  cat $FILENAME | while read LINE
  do
    # 忽略用“#”号注释的行
    [[ $var =~ ^#.* ]] && continue
    
    echo "$LINE"
    # 拆分字符串到数组
    str=$LINE
    OLD_IFS="$IFS"
    IFS=":"
    arr=($str)
    IFS="$OLD_IFS"

    # 获取原IP及现IP
    old_host=${arr[0]}
    new_host=${arr[1]}
    # 将配置文件中的原IP替换为现IP
    sed -i "s/$old_host/$new_host/g" ./ai.config
  done
}

function main() {
  [ "$#" -gt 0 ] || { usage >&2; exit 2; }

  case "$1" in
      (start)
          [ "$#" -eq 1 ] || { usage >&2; exit 2; }
	   update_ips
           # 执行集群迁移脚本
           ./cluster-migration.sh
            ;;
      (post)
	  [ "$#" -eq 1 ] || { usage >&2; exit 2; }
	  ansible-playbook -i "clusters/ai/hosts" -e "@clusters/ai/config.yml" "playbooks/205.post-migration.yml" || return 1
	  ;;
      (*)
          usage
          exit 0
          ;;
  esac
}
main "$@"
