#!/bin/bash
PackageDir=/usr/local/src

# 定义颜色函数
color(){
    case $1 in
        "red") echo -e "\033[31m$2\033[0m" ;;     # 红色
        "green") echo -e "\033[32m$2\033[0m" ;;   # 绿色
        "yellow") echo -e "\033[33m$2\033[0m" ;;  # 黄色
        "blue") echo -e "\033[34m$2\033[0m" ;;    # 蓝色
        *) echo "$2" ;;
    esac
}

Install_Filebeat(){
        yum remove -y filebeat
        if [ -d "/var/lib/filebeat/" ];then
                rm -rf /var/lib/filebeat
        fi

        if [ -d "/etc/filebeat/" ];then
                rm -rf /etc/filebeat/
        fi
        cd $PackageDir
        if [ ! -f "filebeat-7.6.2-x86_64.rpm" ]; then
                wget http://54.179.201.103:8001/filebeat-7.6.2-x86_64.rpm
        fi
        yum localinstall filebeat-7.6.2-x86_64.rpm -y
        systemctl enable filebeat
        systemctl enable filebeat
        rm -f /etc/filebeat/filebeat.yml
}

Create_Config(){

Ipaddr=`ip addr show eth0 | awk -F "[ /]+" '/inet /{print $3}'|awk -F '[.]' '{print $4}'`
services=`ls /home/ec2-user/application/`
cat>>/etc/filebeat/filebeat.yml<<EOF
filebeat.inputs:
EOF
for service in $services
do
	if [[ $service =~ stats ]] || [[ $service =~ elotcmd ]] || [[ $service == openfire_virtual_client ]] || [[ $service =~ bak$ ]] || [[ $service =~ not-use ]] || [[ $service =~ pargo ]];then
                 continue
        fi
cat>>/etc/filebeat/filebeat.yml<<EOF
- type: log
  tail_files: true
  backoff: "1s"
  paths:
      - /home/ec2-user/application/$service/logs/info.log
  fields:
    type: web$Ipaddr-$service-info
  fields_under_root: true
  multiline:
    pattern: '^\['
    negate: true
    match: after
- type: log
  tail_files: true
  backoff: "1s"
  paths:
      - /home/ec2-user/application/$service/logs/error.log
  fields:
    type: web$Ipaddr-$service-error
  fields_under_root: true
  multiline:
    pattern: '^\['
    negate: true
    match: after

EOF
done

        echo -n $(color "green" "请输入topic(例如：第二套：aws02，第三套:aws03......)：") 
        read topic
        echo $(color "blue" "你输入的topic为：$topic")

cat>>/etc/filebeat/filebeat.yml<<EOF
close_older: 30m
force_close_files: true


processors:
- drop_fields:
    fields: ["log.file.path","ecs.version","agent.ephemeral_id","agent.id","agent.type","agent.version","agent.name","input.type","log.offset","host.name","agent.hostname","tags"]

output:
  kafka:
    hosts: ["192.168.10.170:9092", "192.168.10.171:9092", "192.168.10.172:9092"]
    topic: $topic
EOF
}


Install_Filebeat
Create_Config
systemctl restart filebeat
