#!/bin/bash

config_selinux(){
   SELINUX_STATUS=$(getenforce)
   if [ ${SELINUX_STATUS} == "Enforcing" ];then
       setenforce 0
   fi
  
   SELINUX_CONFIG_STATUS=$(grep "^SELINUX=" /etc/selinux/config)
   if [ $SELINUX_CONFIG_STATUS == "SELINUX=enforcing" ];then
       sed -i s/SELINUX=enforcing/SELINUX=disabled/g /etc/selinux/config
   fi
}

sysctl_config(){
    grep "vm.max_map_count" /etc/sysctl.conf &> /dev/null
  if [  $? -ne 0 ];then
    echo "vm.max_map_count=262144" >> /etc/sysctl.conf
  fi
    grep "fs.file-max" /etc/sysctl.conf &> /dev/null
  if [ $? -ne 0 ];then
    echo "fs.file-max=65536" >> /etc/sysctl.conf
  fi
    sysctl -p
}

close_firewalld(){
    systemctl disable firewalld
    systemctl stop firewalld
}


install_docker(){
    tar -zxvf Install_Packages/docker-ce-packages.tar.gz -C /tmp/
    yum -y localinstall /tmp/docker-ce-packages/*.rpm
    systemctl enable docker
    systemctl start docker
}

docker_init(){
    if docker node ls &> /dev/null;then
       echo "swarm exist"
    else
      docker swarm leave --force
      docker swarm init
   fi
    docker node update --label-add nodetype=elk $(docker node ls|grep -v ID|awk '{print $1}')
}

install_docker_compose(){
    cp -rf Install_Packages/docker-compose /usr/local/sbin/docker-compose
    chmod +x /usr/local/sbin/docker-compose
}

create_dir(){
    mkdir -p /elkdata/elasticsearch
    mkdir -p /elkdata/kibana 
}

load_images(){
    docker load -i Install_Packages/elk.tar
    docker load -i Install_Packages/portainer.tar
}

deploy_service(){
    docker stack deploy -c Install_Packages/docker-compose-elk.yml elk
}

portainer_install(){
    docker volume create portainer_data
    docker run -d -p 9000:9000 -l portainer=portainer --restart=always -v /var/run/docker.sock:/var/run/docker.sock -v portainer_data:/data portainer/portainer

}

main(){
    config_selinux
    close_firewalld
    sysctl_config
    install_docker
    docker_init
    install_docker_compose
    create_dir
    load_images
    deploy_service
    portainer_install
}

main
