#!/bin/bash 

# ********************************************** ***************************** #
# File Name: os_chg_syslogconfig.sh
# Description: change syslog-ng config
# Input: 
# Output: none
# Author:
# Created: 2016-04-26
# Function List：
# History 
# 1.Date: 2016-04-26
#   Author:
#   Modification: Hima V100R003 requirements implement
# **************************************************************************** #

source /OSM/script/os_load_base.sh
if [ -f "/etc/sysconfig/syslog" ];then
. /etc/sysconfig/syslog
fi
BINDIR=/sbin

G_SYSLOG_CONF_DIR=/etc/rsyslog.d
G_SYSLOG_CONF_FILENAME=omm_syslog.conf
G_SYSLOG_CONF_FILE=$G_SYSLOG_CONF_DIR/$G_SYSLOG_CONF_FILENAME
G_DEFAULT_CA_FILE=$G_SYSLOG_CONF_DIR/"defaultCA.crt"
G_TMP_CA_KEY_FILE=$G_SYSLOG_CONF_DIR/"ca.key"
G_SYSTEM_SYSLOG_CONF_FILE="/etc/rsyslog.conf"
G_SYSLOG_CONF_FILE_TMP="/tmp/tmp_syslog_conf_$$"
G_OMM_SYSLOG_TEMPLATE_NAME="ommformat"
SYSLOG_NAME='syslog'
IP_ADDR1="0.0.0.0"
IP_ADDR2="0.0.0.0"
IP_ADDR3="0.0.0.0"
IP_ADDR4="0.0.0.0"

G_PORT="514"
G_CHANNEL="1"

G_CA_PATH=""
G_CERT_PATH=""
G_KEY_PATH=""
G_SYSLOG_ENABLE=""
G_SECURITYLOG_ENABLE=""

CHANNEL_UDP="1"
CHANNEL_TCP="2"
CHANNEL_TLS="3"
# --------------------------  functions  ----------------------- ------------- #
# **************************************************************************** #
# Function Name: os_help
# Description: help 
# Parameter: 
# Return: 
# **************************************************************************** #
OS_Help()
{
    echo "USAGE: $0 -a IpAddr1 -b IpAddr2 -c IpAddr3 -d IpAddr4 -p port -t channel -m method -L SyslogEnable -M SecurityEnable"
    echo "-a IpAddr1"
    echo "-b IpAddr2"
    echo "-c IpAddr3"
    echo "-d IpAddr4"
	echo "-p port"
	echo "-t channel 1--UDP;2--TCP;3--TCP+SSL/TLS"
    echo "-m method 0--no edit;1--delete server ip;2--modify server ip"
    echo "-L SyslogEnable 0--disable;1--enable"
    echo "-M SecuritylogEnable 0--disable;1--enable"
    exit 1
}

# **************************************************************************** #
# Function Name: func_add_ip_to_config
# Description: clear all ip line from config file 
# Parameter: $1: destination name     $2: remote server ip
# Return: void
# **************************************************************************** #
func_clear_config()
{
	echo "#IP=${IP_ADDR1},${IP_ADDR2},${IP_ADDR3},${IP_ADDR4}" > ${G_SYSLOG_CONF_FILE}
}

# **************************************************************************** #
# Function Name: func_add_ip_to_config
# Description: add new address to config file 
# Parameter: $1: destination name     $2: remote server ip
# Return: void
# **************************************************************************** #
func_add_one_ip_to_config()
{
    local ip_addr=$1
	local dest=$2
	local head="@"
	local protocal="udp"
	local actionQueueFileName=`echo $1 | sed 's/[.:]/_/g'`
	local template=""
	
	if [ $G_CHANNEL = $CHANNEL_UDP ];then
		head="@"
		protocal="udp"
	else
		head="@@"
		protocal="tcp"
	fi
	if [ $G_SYSLOG_FORMAT -eq 2 ];then
		template=";${G_OMM_SYSLOG_TEMPLATE_NAME}"
	fi
    if [ "${ip_addr}" != "0.0.0.0" ];then
		echo "\$ActionQueueType LinkedList" >> ${dest}
		echo "\$ActionResumeRetryCount 3" >> ${dest}
		echo "\$ActionQueueFileName queue_67_$actionQueueFileName" >> ${dest}
		echo "\$ActionQueueSaveOnShutdown on" >> ${dest}
        L_TMP1=`echo "${ip_addr}" | grep ":"`
        if [ -n "${L_TMP1}" ]; then
            echo "local6.* ${head}[${ip_addr}]:${G_PORT}${template}">> ${dest}
            echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
    
            if [ $G_SYSLOG_ENABLE -eq "1" ] && [ $G_SECURITYLOG_ENABLE -eq "1" ];then
                echo "\$ActionQueueType LinkedList" >> ${dest}
                echo "\$ActionResumeRetryCount 3" >> ${dest}
                echo "\$ActionQueueFileName queue_1_$actionQueueFileName" >> ${dest}
                echo "\$ActionQueueSaveOnShutdown on" >> ${dest}
                echo "local1.info ${head}[${ip_addr}]:${G_PORT}${template}">> ${dest}
            fi
        else
            echo "local7.* ${head}${ip_addr}:${G_PORT}${template}">> ${dest}
            echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
    
            if [ $G_SYSLOG_ENABLE -eq "1" ] && [ $G_SECURITYLOG_ENABLE -eq "1" ];then
                echo "\$ActionQueueType LinkedList" >> ${dest}
                echo "\$ActionResumeRetryCount 3" >> ${dest}
                echo "\$ActionQueueFileName queue_1_$actionQueueFileName" >> ${dest}
                echo "\$ActionQueueSaveOnShutdown on" >> ${dest}
                echo "local1.info ${head}${ip_addr}:${G_PORT}${template}">> ${dest}
                echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
            fi
        fi
    
        if [ $G_SYSLOG_ENABLE -eq "1" ] && [ $G_SECURITYLOG_ENABLE -eq "1" ];then
            echo -e "if ( \$programname == \"sshd\" and (\$msg contains \"Failed password\" or \$msg contains \"Failed publickey\") ) then {\n\t action(type=\"omfwd\" Target=\"${ip_addr}\" Port=\"${G_PORT}\" Protocol=\"${protocal}\" queue.filename=\"queue_ssh_$actionQueueFileName\" queue.type=\"LinkedList\" action.resumeretrycount=\"3\" queue.saveonshutdown=\"on\")\n}"  >> ${dest}
            echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
        fi
    fi
}

func_modify_config()
{
	echo "#IP=${IP_ADDR1},${IP_ADDR2},${IP_ADDR3},${IP_ADDR4}" > ${G_SYSLOG_CONF_FILE_TMP}
	echo "\$ActionQueueTimeoutEnqueue 1000" >> ${G_SYSLOG_CONF_FILE_TMP}
	echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
	if [ $G_SYSLOG_FORMAT -eq 2 ];then
		echo "\$template $G_OMM_SYSLOG_TEMPLATE_NAME,\"<%PRI%>%TIMESTAMP% $G_SYSLOG_HOST_NAME %syslogtag% %msg%\"" >> ${G_SYSLOG_CONF_FILE_TMP}
	fi
	if [ "${G_CHANNEL}" = "${CHANNEL_TLS}" ];
	then
		echo "\$DefaultNetstreamDriver gtls" >> ${G_SYSLOG_CONF_FILE_TMP}
		echo "\$ActionSendStreamDriverMode 1" >> ${G_SYSLOG_CONF_FILE_TMP}
		
		# 当CA证书存在时，ActionSendStreamDriverAuthMode设置成x509/certvalid，即校验服务端证书。#
		# 当CA证书不存在时，ActionSendStreamDriverAuthMode设置成anon，即不校验服务端证书，但是由于rsyslog的bug，此时仍必须配置CA证书路径，可以任意指定一个存在的文件。#
		if [ -n "${G_CA_PATH}" ] && [ -f "${G_CA_PATH}" ];then
			echo "\$ActionSendStreamDriverAuthMode x509/certvalid" >> ${G_SYSLOG_CONF_FILE_TMP}
			echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
			echo "\$DefaultNetstreamDriverCAFile ${G_CA_PATH}" >> ${G_SYSLOG_CONF_FILE_TMP}
			if [ -f "$G_DEFAULT_CA_FILE" ];then
				rm "${G_DEFAULT_CA_FILE}"
			fi
		else
			echo "\$ActionSendStreamDriverAuthMode anon" >> ${G_SYSLOG_CONF_FILE_TMP}
			echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
			if [ ! -f "$G_DEFAULT_CA_FILE" ];then
				openssl req -x509 -nodes -days 3650 -subj '/C=CN/ST=ShaanXi/L=XiAn/O=Huawei/OU=OMM/CN=MMT/emailAddress=support@huawei.com' -newkey rsa:2048 -keyout "$G_TMP_CA_KEY_FILE" -out "$G_DEFAULT_CA_FILE"
				chmod 400 "${G_DEFAULT_CA_FILE}"
				rm "$G_TMP_CA_KEY_FILE"
			fi
			if [ -f "$G_DEFAULT_CA_FILE" ];then
				echo "\$DefaultNetstreamDriverCAFile ${G_DEFAULT_CA_FILE}" >> ${G_SYSLOG_CONF_FILE_TMP}
			else
				echo "\$DefaultNetstreamDriverCAFile /OSM/conf/mmt.pem" >> ${G_SYSLOG_CONF_FILE_TMP}
			fi
			
		fi
		
		if [ -n "${G_CERT_PATH}" ] && [ -f "${G_CERT_PATH}" ] && [ -n "${G_KEY_PATH}" ] && [ -f "${G_KEY_PATH}" ];then
			echo "\$DefaultNetstreamDriverCertFile ${G_CERT_PATH}" >> ${G_SYSLOG_CONF_FILE_TMP}
			echo "\$DefaultNetstreamDriverKeyFile ${G_KEY_PATH}" >> ${G_SYSLOG_CONF_FILE_TMP}
		fi
	else
		if [ -f "$G_DEFAULT_CA_FILE" ];then
			rm "${G_DEFAULT_CA_FILE}"
		fi
	fi
	
	echo "" >> ${G_SYSLOG_CONF_FILE_TMP}
	
	func_add_one_ip_to_config  ${IP_ADDR1} ${G_SYSLOG_CONF_FILE_TMP}
    func_add_one_ip_to_config  ${IP_ADDR2} ${G_SYSLOG_CONF_FILE_TMP}
    func_add_one_ip_to_config  ${IP_ADDR3} ${G_SYSLOG_CONF_FILE_TMP}
    func_add_one_ip_to_config  ${IP_ADDR4} ${G_SYSLOG_CONF_FILE_TMP}
	
	cp -af ${G_SYSLOG_CONF_FILE_TMP} ${G_SYSLOG_CONF_FILE}
	rm -f ${G_SYSLOG_CONF_FILE_TMP}
	chmod 640 ${G_SYSLOG_CONF_FILE}
}

#----------------------------  main  ----------------------------------------- #
if [ $# -lt 1 ];then 
    OS_Help
fi

while getopts "a:b:c:d:p:t:A:C:K:L:M:F:N:" options 2>/dev/null
do
    case $options in
        a) IP_ADDR1=$OPTARG
        ;;
        b) IP_ADDR2=$OPTARG
        ;;
        c) IP_ADDR3=$OPTARG
        ;;
        d) IP_ADDR4=$OPTARG
        ;;
		p) G_PORT=$OPTARG
        ;;
		t) G_CHANNEL=$OPTARG
        ;;
		A) G_CA_PATH=$OPTARG
        ;;
		C) G_CERT_PATH=$OPTARG
        ;;
		K) G_KEY_PATH=$OPTARG
        ;;
		L) G_SYSLOG_ENABLE=$OPTARG
        ;;
		M) G_SECURITYLOG_ENABLE=$OPTARG
        ;;
		F) G_SYSLOG_FORMAT=$OPTARG
	;;
		N) G_SYSLOG_HOST_NAME=$OPTARG
	;;
		*) OS_Help
        ;;
    esac
done

#判断syslog配置文件是否存在
if [ ! -f "${G_SYSLOG_CONF_FILE}" ];then
    OS_echo "[omm_chg_syslog_config.sh] ${G_SYSLOG_CONF_FILE} does not exit, create it."
	touch "${G_SYSLOG_CONF_FILE}"
fi


#ADD_IP：在syslog-ng.conf文件中增加配置
func_modify_config

#修改配置文件后，重启syslog服务
L_RESULT=0
if [ -f "/etc/init.d/syslog" ];then
	/etc/init.d/syslog restart
	L_RESULT=$?
	pid=$(ps -ef | grep $SYSLOG_NAME | grep '/sbin/rsyslogd' | grep -v grep | awk '{print $2}')
	cgroup_manage.sh -i $pid end
else
	systemctl restart rsyslog
	L_RESULT=$?
fi
if [ "${L_RESULT}" != "0" ];then
	OS_echo "[omm_chg_syslog_config.sh]restart syslog error."
	exit 1
fi
OS_echo "[omm_chg_syslog_config.sh]Config syslog conf success."

exit 0
