#!/bin/bash
#
#*****************************************************
#File Name    : install_keepalived.sh
#Author       : guokai
#Mail         : xxx@163.com
#Create Time  : 2022-04-15 14:44:47
#Description  : The test script
#*****************************************************
SRC_DIR=/usr/local/src
KEEPALIVED_URL=https://keepalived.org/software/
NEIBU_URL=http://58.220.50.162:7777/download/
KEEPALIVED_FILE=keepalived-2.0.20
TAR=.tar.gz
KEEPALIVED_INSTALL_DIR=/usr/local/keepalived
CPUS=`lscpu | awk '/^CPU\(s\):/{print $2}'`

color () {
	RES_COL=60
	MOVE_TO_COL="echo -en \\033[${RES_COL}G"
	SETCOLOR_SUCCESS="echo -en \\033[1;32m"
	SETCOLOR_FAILURE="echo -en \\033[1;31m"
	SETCOLOR_WARNING="echo -en \\033[1;33m"
	SETCOLOR_NORMAL="echo -en \E[0m"
	echo -n "$2" && $MOVE_TO_COL
	echo -n "["
	if [ $1 = "success" -o $1 = "0" ] ;then ${SETCOLOR_SUCCESS}
		echo -n $"  OK  "
	elif [ $1 = "failure" -o $1 = "1" ] ;then ${SETCOLOR_FAILURE}
		echo -n $"FAILED"
	else 
		${SETCOLOR_WARNING}
		echo -n $"WARNING"
	fi
	${SETCOLOR_NORMAL}
	echo -n "]"
	echo
}



check () {
	[ -e ${KEEPALIVED_INSTALL_DIR} ] && { color 1 "keepalived 已安装,请卸载后再安装" ; exit; }
	cd ${SRC_DIR}
	if [ -e ${KEEPALIVED_FILE}${TAR} ];then
		color 0 "相关文件已准备好"
	else
		color 0 "开始下载 keepalived 源码包"
		wget ${NEIBU_URL}${KEEPALIVED_FILE}${TAR} 
		[ $? -ne 0 ] && { color 1 "下载 ${KEEPALIVED_FILE}${TAR}文件失败" ; exit ; }
		color 0 "开始安装ansible"
		dnf install -y ansible-core sshpass
	fi
}

install_keepalived(){
	color 0 "开始安装 keepalived"
	dnf -y install gcc curl openssl-devel libnl3-devel 
	cd ${SRC_DIR}
	tar -zxf ${KEEPALIVED_FILE}${TAR} -C /usr/local/src
	cd ${SRC_DIR}/${KEEPALIVED_FILE}
	./configure --prefix=/usr/local/keepalived --disable-fwmark
	make -j $CPUS && make install
	mkdir /etc/keepalived
	cp ${KEEPALIVED_INSTALL_DIR}/etc/keepalived/keepalived.conf /etc/keepalived
	systemctl enable --now keepalived &> /dev/null 
    systemctl status keepalived 
	color 0 "keepalived 安装完成" 
	
}

check
install_keepalived
