#!/usr/bin/env bash
#--------------------------------------------------------------------------------#
#
# @for linux centos 6.5
# @desc 基础函数
# @data 2016/09/10
# @author logonmy
#
#--------------------------------------------------------------------------------#
#set -e

##==============================  Base  Setting  ================================##
#yum源的来源[aliyun]
YumReposUri="http://mirrors.aliyun.com/repo/Centos-6.repo"

#Epel源的来源[中国科学技术大学]
#EpelReposUri="http://mirrors.ustc.edu.cn/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm"
#rpm -Uvh ${EpelReposUri} 2>&1 >/dev/null
#rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-6

#Epel源的来源[aliyun]
EpelReposUri="http://mirrors.aliyun.com/repo/epel-6.repo"

# 应用日志存放处
LogDir=/data/logs
[[ ! -d ${LogDir} ]] && mkdir -p ${LogDir} 2>&1 >/dev/null

# 隐式 安装锁存放处
LockDir=/data/.evncores
[[ ! -d ${LockDir} ]] && mkdir -p ${LockDir} 2>&1 >/dev/null

#安装信息 详细保护处
InstallationLogDir=/data/install.log
[[ ! -d ${InstallationLogDir} ]] &&  mkdir -p ${InstallationLogDir} 2>&1 >/dev/null

SYS_VERSION=6
IS_64BIT=TRUE
##==========================end   Base  Setting  ================================##


##============================ print color text =================================##

Color_Text()
{
  echo -e " \e[0;$2m$1\e[0m"
}

Echo_Red()
{
  echo $(Color_Text "$1" "31")
}

Echo_Green()
{
  echo $(Color_Text "$1" "32")
}

Echo_Yellow()
{
  echo $(Color_Text "$1" "33")
}

Echo_Blue()
{
  echo $(Color_Text "$1" "34")
}
##==============================end print color text============================##


##================================ sys info ====================================##
function Get_OS_Bit()
{
    if [[ `getconf WORD_BIT` = '32' && `getconf LONG_BIT` = '64' ]] ; then
        IS_64BIT=TRUE
    else
        IS_64BIT=FALSE
    fi
}


function Get_Dist_Name()
{
    if grep -Eqi "CentOS" /etc/issue || grep -Eq "CentOS" /etc/*-release; then
        DISTRO='CentOS'
        PM='yum'
    elif grep -Eqi "Red Hat Enterprise Linux Server" /etc/issue || grep -Eq "Red Hat Enterprise Linux Server" /etc/*-release; then
        DISTRO='RHEL'
        PM='yum'
    elif grep -Eqi "Aliyun" /etc/issue || grep -Eq "Aliyun" /etc/*-release; then
        DISTRO='Aliyun'
        PM='yum'
    elif grep -Eqi "Fedora" /etc/issue || grep -Eq "Fedora" /etc/*-release; then
        DISTRO='Fedora'
        PM='yum'
    elif grep -Eqi "Debian" /etc/issue || grep -Eq "Debian" /etc/*-release; then
        DISTRO='Debian'
        PM='apt'
    elif grep -Eqi "Ubuntu" /etc/issue || grep -Eq "Ubuntu" /etc/*-release; then
        DISTRO='Ubuntu'
        PM='apt'
    elif grep -Eqi "Raspbian" /etc/issue || grep -Eq "Raspbian" /etc/*-release; then
        DISTRO='Raspbian'
        PM='apt'
    else
        DISTRO='unknow'
    fi
    Echo_Yellow 'linux : '${DISTRO}' & PM command : '${PM}
    Get_OS_Bit
}


function Get_Sys_Version()
{
    Get_Dist_Name
    if [[ "${DISTRO}" = "RHEL" ]] || [[ "${DISTRO}" = "CentOS" ]]; then
        if grep -Eqi "release 5." /etc/redhat-release; then
            echo ''
            Echo_Green "Current SYS Version: RHEL Ver 5"
            SYS_VERSION='5'
        elif grep -Eqi "release 6." /etc/redhat-release; then
            Echo_Green "Current SYS Version: RHEL Ver 6"
            SYS_VERSION='6'
        elif grep -Eqi "release 7." /etc/redhat-release; then
            Echo_Green "Current SYS Version: RHEL Ver 7"
            SYS_VERSION='7'
        fi
    fi
}

Get_Sys_Version

##================================ end sys info =================================##

##================================== tool function ==============================##
# change yum-repo
function Get_Init_Status(){
    if [[ -s ${LockDir}/$1 ]] || [[ -f ${InstallationLogDir}/$1 ]]
    then
        echo 'past'
    else
        echo 'fresh'
    fi
}

function Change_Yum_Repo(){
    local flg=yum_repo
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Change Yum repo ..."
        cd /etc/yum.repos.d/
        [[ ! -f CentOS-Base.repo.bakckup ]] && mv CentOS-Base.repo  CentOS-Base.repo.bakckup 2>&1 >/dev/null
        wget -O "CentOS-Base.repo" ${YumReposUri}
        yum clean all -y
        yum makecache -y
#        yum update -y | tee ${InstallationLogDir}/${flg}
        echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Add_Epel_Repo(){
    local flg=yum_epel
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Add EPEL repo..."
        cd /etc/yum.repos.d/
        [[ ! -f epel.repo.backup ]] && [[ -f epel.repo ]] && mv epel.repo epel.repo.backup
        [[ -f epel-testing.repo.backup ]] && [[ -f epel-testing.repo ]] && mv epel-testing.repo epel-testing.repo.backup
        wget -O "epel.repo" ${EpelReposUri} |tee ${InstallationLogDir}/${flg}
        echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Shutdown_IPV6(){
    # 关闭 IPv6
    local flg=shut_ipv6
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] turn down IPV6..."
        local DISIPV6FILE=/etc/modprobe.d/ipv6off.conf
        local NetWorkScript=/etc/sysconfig/network
        local HostsFile=/etc/hosts
        [[ ! -s ${DISIPV6FILE} ]] && touch ${DISIPV6FILE};
        sed -i '/AddressFamily any/ s@#@@g' /etc/ssh/sshd_config
        sed -i '/ListenAddress 0.0.0.0/ s@#@@g' /etc/ssh/sshd_config
        echo "alias net-pf-10 off" >> ${DISIPV6FILE}
        echo "options ipv6 disable=1" >> ${DISIPV6FILE}
        echo "NETWORKING_IPV6=no" >>${NetWorkScript}
        sed -i 's@^::1@#&@g' ${HostsFile}
        echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Disable_Selinux(){
    # 关闭 selinux
    local flg=disable_selinux
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Disable SELINUX..."
        if [ "`/usr/sbin/getenforce`" = "Enforcing" ];then
            sed -ri 's/^(SELINUX=).*/\1disabled/g' /etc/selinux/config
            setenforce 0
        fi
        echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Set_Ntp(){
    # 时间同步
    local flg=set_ntp
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Set ntp..."
        yum install -y ntp |tee ${InstallationLogDir}/${flg}
        /usr/sbin/ntpdate pool.ntp.org 2>&1 >/dev/null
        echo "1 */5 * * * /usr/sbin/ntpdate pool.ntp.org 2>&1 > /dev/null " >> /var/spool/cron/root
        echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Set_Lang(){
    # set language
    local flg=language
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Set LANG..."

cat > /etc/sysconfig/i18n<<EOFS
LANG="en_US.UTF-8"
SYSFONT="latarcyrheb-sun16"
EOFS

cat > ~/.vimrc <<EOFV
set fileencodings=utf-8,ucs-bom,gb18030,gbk,gb2312,cp936
set termencoding=utf-8
set encoding=utf-8
EOFV
    source /etc/sysconfig/i18n
    echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Set_Timezone(){
    Echo_Blue "Set timezone..."
    rm -rf /etc/localtime 2>&1 >/dev/null
    ln -s /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
}

function Set_Limit(){
    #set limit
    local flg=limit_conf
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Set Limit..."
cat > /etc/security/limits.conf <<EOF
* soft    nofile  1024000
* hard    nofile  1024000
* soft    nproc   unlimited
* hard    nproc   unlimited
* soft    core    unlimited
* hard    core    unlimited
* soft    memlock unlimited
* hard    memlock unlimited
EOF
    local l_file=/etc/security/limits.d/90-nproc.conf
    [[ -f ${l_file} ]] && mv ${l_file} ${l_file}.backup 2>&1 >/dev/null
    echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

function Set_Sysctl(){
    # set sysctl
    local flg=sysctl_conf
    if [[ "$(Get_Init_Status "${flg}")" = "fresh" ]];
    then
        Echo_Blue "[+] Set Sysctl..."
        [[ ! -d /data/corefiles ]] && mkdir -p /data/corefiles && chmod 0777 -R /data/corefiles
        [[ ! -f /etc/sysctl.conf.backup ]] && /bin/cp -f /etc/sysctl.conf /etc/sysctl.conf.backup 2>&1 >/dev/null
cat > /etc/sysctl.conf <<EOFCTL
# Kernel sysctl configuration file for Red Hat Linux
#
# For binary values, 0 is disabled, 1 is enabled.  See sysctl(8) and
# sysctl.conf(5) for more details.

# Controls IP packet forwarding
net.ipv4.ip_forward = 0

# Controls source route verification
net.ipv4.conf.default.rp_filter = 1

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0

# Controls whether core dumps will append the PID to the core filename
# Useful for debugging multi-threaded applications
kernel.core_uses_pid = 1

# Controls the use of TCP syncookies
net.ipv4.tcp_syncookies = 1

# Controls the maximum size of a message, in bytes
kernel.msgmnb = 65536

# Controls the default maxmimum size of a mesage queue
kernel.msgmax = 65536

# Controls the maximum shared segment size, in bytes
kernel.shmmax = 68719476736
# kernel.shmmax = 4294967295

# Controls the maximum number of shared memory segments, in pages
kernel.shmall = 4294967296
# kernel.shmall = 268435456

net.ipv4.tcp_syncookies=1
net.ipv4.tcp_fin_timeout = 5
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.route.gc_timeout = 100
net.ipv4.ip_local_port_range = 30000 65000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_syn_retries = 1
#net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 1
#net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 262144
net.core.netdev_max_backlog = 262144
net.core.somaxconn = 262144
net.ipv4.tcp_mem = 94500000 915000000 927000000

# add by Micah
net.ipv4.tcp_max_tw_buckets = 262144
net.core.rmem_max = 16777216
net.core.wmem_max = 16777216
net.ipv4.tcp_rmem = 4096 87380 16777216
net.ipv4.tcp_wmem = 4096 65536 16777216
net.ipv4.tcp_timestamps = 1
net.ipv4.tcp_window_scaling = 1
net.ipv4.tcp_sack = 0
net.ipv4.tcp_no_metrics_save = 1
net.ipv4.tcp_max_orphans = 262144
fs.file-max = 10485760
#net.nf_conntrack_max = 10485760
#net.netfilter.nf_conntrack_max = 10485760
#net.netfilter.nf_conntrack_checksum = 0

EOFCTL
    sysctl -p /etc/sysctl.conf |tee ${InstallationLogDir}/${flg}
    echo `date '+%Y-%m-%d %H:%M:%S.%N'` > ${LockDir}/${flg}
    fi
}

##======================= end tool function ========================##
#Echo_Green "init the fresh host"
Echo_Green "hello world"

Echo_Yellow "
Add_Epel_Repo
Change_Yum_Repo
Shutdown_IPV6
Disable_Selinux
Set_Lang
Set_Ntp
Set_Limit
Set_Sysctl
"

