######################################################################
####function:install keepalived
####author:lance_cao
####create date:2019-11
####modify date:2019-11
######################################################################

#!/bin/bash

set -e
echo "[`date +'%F %H:%M:%S'`] [INFO] useage : sh install_keepalived.sh [setup_mode] [local_ip] [nginx_vip]"

if [ $# -ne 3 ]; then
    echo "$(basename $0): Missing script argument"
    echo "$(basename $0) [setup_mode] [local_ip] [nginx_vip]"
    exit 1
fi
 
pd=$PWD
setup_mode=$1
IP=$2
VIP=$3
ROUTE_ID=${VIP##*.}


# yum install net-tools.x86_64 -y

line=$(expr $(ifconfig|grep "$IP" -n|awk -F: '{print $1}') - 1 )
ENS=`ifconfig|sed -n "$line p"|awk -F: '{print $1}'`
HOSTNAME=`hostname`
# yum -y install openssl-devel
# yum -y install libnl libnl-devel
# yum install -y libnfnetlink-devel

tar -zxvf keepalived-1.4.0.tar.gz
cd $pd/keepalived-1.4.0
./configure --prefix=/usr/local/keepalived
make && make install

if [ ! -d "/etc/keepalived/" ];then
	mkdir /etc/keepalived/
fi
cd $pd
if [ $setup_mode -eq "1" ];then
   cp -rf keepalived_master.conf /etc/keepalived/keepalived.conf
else
   cp -rf keepalived_backup.conf /etc/keepalived/keepalived.conf
fi
chmod 644 /etc/keepalived/keepalived.conf

cp -rf nginx_check.sh /etc/keepalived/nginx_check.sh
chmod +x /etc/keepalived/nginx_check.sh
sed -i s/eth0/$ENS/g /etc/keepalived/keepalived.conf
sed -i s/hostname/$HOSTNAME/g /etc/keepalived/keepalived.conf
sed -i s/host_ip/$IP/g /etc/keepalived/keepalived.conf
sed -i s/nginx_vip/$VIP/g /etc/keepalived/keepalived.conf
sed -i s/route_id_33/$ROUTE_ID/g /etc/keepalived/keepalived.conf

## server options ##
systemctl daemon-reload
systemctl restart keepalived
systemctl enable keepalived

echo "Keepalived install success "
