#/bin/bash
set -e 

BASE=$(grep -E 'BASE' ./ai.config|cut -d'=' -f2)
SSH_PORT=$(grep -E 'SSH_PORT' ./ai.config|cut -d'=' -f2)
MINIO_URL=$(grep -E 'MINIO_URL' $BASE/ai.config|cut -d'=' -f2)
mkdir -p $BASE/down

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
}

function check_os() {
  RELEASE_OS=$(grep -E 'Release_OS' $BASE/Release |cut -d'=' -f2|awk '{print $1}')
  if [[ `cat /etc/os-release` =~ Ubuntu ]];then
    OS_VERSION=$(grep -E 'VERSION_ID' /etc/os-release | sed "s/'//g;s/\"//g" | cut -d'=' -f2)
    if [[ $RELEASE_OS =~ $OS_VERSION ]];then
      logger info "当前安装包for $RELEASE_OS 支持当前操作系统 ubuntu$OS_VERSION 部署"
    else 
      { logger error "当前安装包for $RELEASE_OS 不支持当前操作系统 ubuntu$OS_VERSION 部署"; return 1; }
    fi
  fi
}

function config_hosts() {
  rm -rf $BASE/ai/prepareinstall/hosts
  echo "[masters]" >> $BASE/ai/prepareinstall/hosts
  cat ai.config  | grep MGR_NODE_IP >> $BASE/ai/prepareinstall/hosts
  echo "[nodes]" >> $BASE/ai/prepareinstall/hosts
  cat ai.config  | grep COMPUTE_NODE >> $BASE/ai/prepareinstall/hosts
  echo "[storages]" >> $BASE/ai/prepareinstall/hosts
  cat ai.config  | grep STORAGE_NODE_IP >> $BASE/ai/prepareinstall/hosts
  sed -i 's/MGR.*IP=//g' $BASE/ai/prepareinstall/hosts
  sed -i 's/COM.*IP[0-9]=//g' $BASE/ai/prepareinstall/hosts
  sed -i 's/STO.*IP[0-9]=//g' $BASE/ai/prepareinstall/hosts
  echo "[all:vars]" >> $BASE/ai/prepareinstall/hosts
  sed -i "/\[all:vars/a base_dir=$BASE" $BASE/ai/prepareinstall/hosts
  echo "ansible_ssh_port=$SSH_PORT" >>$BASE/ai/prepareinstall/hosts
}

function get_sys_pkg() {
  if [[ `cat /etc/os-release` =~ CentOS ]];then
    if [[ `cat /etc/yum.conf` =~ exclude ]];then
      logger info "已关闭内核自动更新"
    else
      echo "exclude=kernel*" >> /etc/yum.conf
      echo "exclude=centos-release*" >>/etc/yum.conf
      logger info "已关闭内核自动更新"
    fi
  elif [[ `cat /etc/os-release` =~ openEuler ]];then
         echo "对openeuler 内核操作，如果有需要"
         yum install unzip python3-libselinux  -y  
  elif [[ `cat /etc/os-release` =~ Ubuntu ]];then
    sed -i 's/1/0/g' /etc/apt/apt.conf.d/10periodic
    sed -i 's/1/0/g' /etc/apt/apt.conf.d/20auto-upgrades
    logger info "已关闭内核自动更新"
  fi

  if [[ ! -f /usr/bin/curl ]];then
    if [[ `cat /etc/os-release` =~ CentOS || `cat /etc/os-release` =~ openEuler || `cat /etc/os-release` =~ Rocky || `cat /etc/os-release` =~ AlmaLinux || `cat /etc/os-release` =~ "Kylin Linux Advanced Server" ]];then
      logger info "正在安装curl"
      yum install curl -y
    elif [[ `cat /etc/os-release` =~ Ubuntu ]];then
      logger info "正在安装curl"
      apt-get install curl -y
    fi
  fi
    
  if [[ `cat /etc/os-release` =~ CentOS ||`cat /etc/os-release` =~ openEuler  || `cat /etc/os-release` =~ Rocky || `cat /etc/os-release` =~ AlmaLinux || `cat /etc/os-release` =~ "Kylin Linux Advanced Server" ]];then
    SYS_PKG_URL="$MINIO_URL/ai-deployer/centos-rpm-packages.tar.gz"
    if [[ -f "$BASE/down/centos-rpm-packages.tar.gz" ]];then
      logger warn "system packages already existed!"
    else
      logger debug "downloading system packages!"
      curl -C- -O --retry 3 "$SYS_PKG_URL" || { logger error "downloading system packages failed"; exit 1; }
      /bin/mv -f "./centos-rpm-packages.tar.gz" "$BASE/down"
      tar zxf "$BASE/down/centos-rpm-packages.tar.gz" -C "$BASE/down"
    fi
  else
    UBUNTU_VERSION=$(grep -E 'VERSION_ID' /etc/os-release | sed "s/'//g;s/\"//g" | cut -d'=' -f2)
    SYS_PKG_URL="$MINIO_URL/ai-deployer/ubuntu-$UBUNTU_VERSION-deb-packages.tar.gz"
    if [[ -f "$BASE/down/ubuntu-$UBUNTU_VERSION-deb-packages.tar.gz" ]];then
      logger warn "system packages already existed!"
    else
      logger debug "downloading system packages!"
      curl -C- -O --retry 3 "$SYS_PKG_URL" || { logger error "downloading system packages failed"; exit 1; }
      /bin/mv -f "./ubuntu-$UBUNTU_VERSION-deb-packages.tar.gz" "$BASE/down/"
      tar zxf "$BASE/down/ubuntu-$UBUNTU_VERSION-deb-packages.tar.gz" -C "$BASE/down"
    fi
  fi
}
function install_ansible() {
  if [[ -f /usr/bin/ansible ]];then
    logger warn "ansible is already installed!"
  else
    #安装ansible
    logger debug "installing ansible!"
    if [[ `cat /etc/os-release` =~ CentOS ]];then
      tar zxf "$BASE/down/centos-rpm-packages/ansible-rpm-packages.tar.gz" -C "$BASE/down/centos-rpm-packages"
      rpm -ivh --force --nodeps $BASE/down/centos-rpm-packages/ansible-rpm-packages/*
    elif [[ `cat /etc/os-release` =~ openEuler ]];then
         yum install lxcfs -y && systemctl  enable lxcfs.service
         sed -i 's#/var/lib/lxc/#/var/lib/#g' /usr/lib/systemd/system/lxcfs.service
         systemctl daemon-reload  &&  systemctl  restart lxcfs.service
         yum install ansible  bash-completion -y
         systemctl stop firewalld &&  systemctl disable firewalld
         sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
         echo "source /usr/share/bash-completion/bash_completion">>/root/.bashrc
         source /root/.bashrc
    elif [[ `cat /etc/os-release` =~ Rocky || `cat /etc/os-release` =~ AlmaLinux ]];then
         sudo dnf install epel-release -y
         yum install lxcfs ansible -y && systemctl  enable lxcfs.service
         sed -i 's#/var/lib/lxc/#/var/lib/#g' /usr/lib/systemd/system/lxcfs.service
         systemctl daemon-reload  &&  systemctl  restart lxcfs.service
         yum install ansible  bash-completion -y
         systemctl stop firewalld &&  systemctl disable firewalld
         sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
         echo "source /usr/share/bash-completion/bash_completion">>/root/.bashrc
         source /root/.bashrc
     elif [[ `cat /etc/os-release` =~ "Kylin Linux Advanced Server" ]];then
         yum update -y
         yum install lxcfs -y && systemctl  enable lxcfs.service
         yum install ansible  bash-completion -y
         systemctl stop firewalld &&  systemctl disable firewalld
         sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
         echo "source /usr/share/bash-completion/bash_completion">>/root/.bashrc
         source /root/.bashrc
    elif [[ `cat /etc/os-release` =~ Ubuntu ]];then
      #tar zxf "$BASE/down/ubuntu-deb-packages/ansible-deb-packages.tar.gz" -C "$BASE/down/ubuntu-deb-packages"
      #dpkg -i $BASE/down/ubuntu-deb-packages/ansible-deb-packages/*
      apt install ansible -y
      apt install python3-pymysql -y
      ansible-galaxy collection install $BASE/community-mysql-3.7.2.tar.gz --ignore-errors
    fi
  fi
  #判断系统中是否有post-reboot.sh
  if [[ -f /usr/local/bin/post-reboot.sh ]];then
    logger warn "post-reboot.sh is already existed!"
  else
    logger debug "downloading post-reboot.sh!"
    /bin/cp -f ./post-reboot.sh  /usr/local/bin/post-reboot.sh
    chmod +x /usr/local/bin/post-reboot.sh
    /bin/cp -f ./post-reboot.service  /usr/lib/systemd/system/post-reboot.service
    systemctl daemon-reload
    systemctl enable post-reboot.service
    systemctl start post-reboot.service
  fi
}
function configure_ssh() {
  if [[ -f /usr/bin/expect ]];then
    logger warn "expect is already installed!"
  else
    #安装expect
    if [[ `cat /etc/os-release` =~ CentOS ]];then
      tar zxf "$BASE/down/centos-rpm-packages/expect-rpm-packages.tar.gz" -C "$BASE/down/centos-rpm-packages"
      rpm -ivh --force --nodeps $BASE/down/centos-rpm-packages/expect-rpm-packages/*
    elif [[ `cat /etc/os-release` =~ openEuler || `cat /etc/os-release` =~ Rocky || `cat /etc/os-release` =~ AlmaLinux || `cat /etc/os-release` =~ "Kylin Linux Advanced Server" ]];then
         yum install expect -y
    elif  [[ `cat /etc/os-release` =~ Ubuntu ]];then
      #tar zxf "$BASE/down/ubuntu-deb-packages/expect-deb-packages.tar.gz" -C "$BASE/down/ubuntu-deb-packages"
      #dpkg -i $BASE/down/ubuntu-deb-packages/expect-deb-packages/*
      apt install expect -y
    fi
  fi

  logger debug "配置免密码登录!"
  #从配置文件获取服务器IP和密码
  serverIPs=$(grep -E 'MGR_NODE_IP|COMPUTE_NODE_IP|HARBOR_NODE_IP' ./ai.config |cut -d'=' -f2|awk '!($1 in IP){IP[$1];print $1}')
  serverPassword=$(grep -r 'SERVER_PASSWORD' ./ai.config)
  serverPassword=${serverPassword#*=}

  #生成密钥
  if [[ ! -f /root/.ssh/id_rsa.pub ]];then
    ssh-keygen -t rsa -b 2048 -N '' -f ~/.ssh/id_rsa
  fi
  # if [[ ! -f /root/.ssh/id_ecdsa.pub ]];then
  #   ssh-keygen -t ecdsa -b 521 -N '' -f ~/.ssh/id_ecdsa
  # fi

  #将生成的密钥发送至目标服务器,自动输入yes和密码
  auto_ssh_copy_id() {
    expect -c "set timeout -1
    spawn ssh-copy-id -p $SSH_PORT $1
    expect {
      *yes/no* {send -- yes\r;exp_continue;}
      *password:* {send -- $2\r;exp_continue;}
      eof        {exit 0;}
    }"
  }
  #遍历需要发送密钥的服务器
  #遍历需要发送密钥的服务器
  ssh_copy_id_to_all(){
    for serverIP in $serverIPs
    do
      auto_ssh_copy_id $serverIP $serverPassword
    done
  }
  ssh_copy_id_to_all
}
config_hosts
get_sys_pkg
install_ansible
configure_ssh
cd $BASE/ai/prepareinstall/
ansible-playbook -i hosts check.yml
