#!/bin/bash

set -o errexit

get_sys_ver() {
cat > /tmp/sys_ver.py <<EOF
import platform
import re

sys_ver = platform.platform()
sys_ver = re.sub(r'.*-with-(.*)-.*',"\g<1>",sys_ver)
if sys_ver.startswith("centos-7"):
    sys_ver = "centos-7"
if sys_ver.startswith("centos-6"):
    sys_ver = "centos-6"
print sys_ver
EOF
echo `python /tmp/sys_ver.py`
}

#判断系统版本
check_sys(){
    local checkType=$1
    local value=$2

    local release=''
    local systemPackage=''
    local packageSupport=''

    . /tmp/ezhttp_sys_check_result > /dev/null 2>&1
    if [[ "$release" == "" ]] || [[ "$systemPackage" == "" ]] || [[ "$packageSupport" == "" ]];then

        if [[ -f /etc/redhat-release ]];then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /etc/issue | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "debian";then
            release="debian"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "ubuntu";then
            release="ubuntu"
            systemPackage="apt"
            packageSupport=true

        elif cat /proc/version | grep -q -E -i "centos|red hat|redhat";then
            release="centos"
            systemPackage="yum"
            packageSupport=true

        else
            release="other"
            systemPackage="other"
            packageSupport=false
        fi
    fi

    echo -e "release=$release\nsystemPackage=$systemPackage\npackageSupport=$packageSupport\n" > /tmp/ezhttp_sys_check_result

    if [[ $checkType == "sysRelease" ]]; then
        if [ "$value" == "$release" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageManager" ]]; then
        if [ "$value" == "$systemPackage" ];then
            return 0
        else
            return 1
        fi

    elif [[ $checkType == "packageSupport" ]]; then
        if $packageSupport;then
            return 0
        else
            return 1
        fi
    fi
}

install_python27() {
    yum groupinstall -y "Development tools"
    yum install -y zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel
    wget https://www.python.org/ftp/python/2.7.14/Python-2.7.14.tgz
    tar zxf Python-2.7.14.tgz
    cd Python-2.7.14
    ./configure
    make && make install
    wget https://bootstrap.pypa.io/ez_setup.py -O - | python
    easy_install pip

}

install_python_modules() {
    if check_sys sysRelease ubuntu;then
        apt-get install -y python-pip gcc python-dev
    elif check_sys sysRelease centos;then
        yum -y install epel-release
        local release=`cat /etc/redhat-release | grep -oE [.0-9]+ | awk -F'.' '{print $1}'`
        if [[ $release == "7" ]];then
            yum -y --enablerepo=epel install python-pip gcc python-devel
        else
            install_python27
        fi    
    fi 

    pip="pip2"
    if check_sys sysRelease centos;then
        local release=`cat /etc/redhat-release | grep -oE [.0-9]+ | awk -F'.' '{print $1}'`
        if [[ $release == "6" ]];then
            pip="pip2.7"
        fi
    fi

    $pip install --upgrade pip==20.0.1
    $pip install --upgrade setuptools
    $pip install Flask==0.12.2
    $pip install requests
    $pip install timeout_decorator
    $pip install pycrypto
    $pip install supervisor
    $pip install psutil
    $pip install Werkzeug==0.16.1
}

install_openresty() {
    if [[ -d "/usr/local/openresty" ]];then
        return
    fi    

    if check_sys sysRelease ubuntu;then
        apt-get -y install perl autoconf automake libtool libcurl3-dev libpcre3-dev libssl-dev zlib1g-dev g++

    elif check_sys sysRelease centos;then
        yum install -y perl autoconf automake libtool curl-devel pcre-devel openssl-devel zlib-devel gcc-c++

    fi 

    # libmaxminddb
    cd /tmp
    #wget http://dl-us.centos.bz/httpguard/libmaxminddb-1.3.2.tar.gz
    wget https://github.com/maxmind/libmaxminddb/releases/download/1.3.2/libmaxminddb-1.3.2.tar.gz
    tar xf libmaxminddb-1.3.2.tar.gz
    cd libmaxminddb-1.3.2
    ./configure
    make && make install
    echo '/usr/local/lib' > /etc/ld.so.conf.d/geoip.conf
    ldconfig

    # geoip2
    cd /tmp
    wget https://github.com/leev/ngx_http_geoip2_module/archive/2.0.tar.gz
    tar xf 2.0.tar.gz

    cd /tmp
    #wget https://ftp.pcre.org/pub/pcre/pcre-8.38.tar.gz
    wget https://sourceforge.net/projects/pcre/files/pcre/8.45/pcre-8.45.tar.gz --no-check-certificate
    tar xf pcre-8.45.tar.gz
    wget https://openresty.org/download/openresty-1.13.6.1.tar.gz
    tar xf openresty-1.13.6.1.tar.gz
    cd openresty-1.13.6.1
    ./configure --prefix=/usr/local/openresty \
                --with-pcre-jit \
                --with-stream \
                --with-stream_ssl_module \
                --with-http_stub_status_module \
                --with-http_realip_module \
                --with-http_addition_module \
                --with-http_auth_request_module \
                --with-http_secure_link_module \
                --with-http_random_index_module \
                --with-http_gzip_static_module \
                --with-http_sub_module \
                --with-http_dav_module \
                --with-http_flv_module \
                --with-http_mp4_module \
                --with-http_gunzip_module \
                --with-threads \
                --with-file-aio \
                --with-stream \
                --with-stream_ssl_module \
                --with-http_ssl_module \
                --with-http_v2_module \
                --without-mail_pop3_module \
                --without-mail_imap_module \
                --without-mail_smtp_module \
                --with-pcre=/tmp/pcre-8.45 \
                --add-dynamic-module=/tmp/ngx_http_geoip2_module-2.0/

    make && make install
    strip /usr/local/openresty/nginx/sbin/nginx
    mkdir -p /usr/local/openresty/nginx/conf/vhost/{certs,error_page}

    if [[ -f "/etc/rc.local" ]]; then
        sed -i '/exit 0/d' /etc/rc.local
        if [[ `grep "/usr/local/openresty/nginx/sbin/nginx" /etc/rc.local` == "" ]];then 
            echo "/usr/local/openresty/nginx/sbin/nginx" >> /etc/rc.local
        fi 
        chmod +x /etc/rc.local 
    fi
   
    if [[ -f "/etc/rc.d/rc.local" ]]; then
        sed -i '/exit 0/d' /etc/rc.d/rc.local
        if [[ `grep "/usr/local/openresty/nginx/sbin/nginx" /etc/rc.d/rc.local` == "" ]];then 
            echo "/usr/local/openresty/nginx/sbin/nginx" >> /etc/rc.d/rc.local
        fi
        chmod +x /etc/rc.d/rc.local 
    fi    
               
    # 下载geoip2数据库
    #mkdir -p /opt/geoip/
    #wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz -O /opt/geoip/GeoLite2-Country.mmdb.gz
    #gunzip -f /opt/geoip/GeoLite2-Country.mmdb.gz

    # 添加定时任务更新geoip2
    #if check_sys sysRelease ubuntu || check_sys sysRelease debian;then
    #    ! grep -q "wget http://geolite.maxmind.com" /var/spool/cron/crontabs/root > /dev/null 2>&1 && echo "01 01 01 * 01 wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz -O /opt/geoip/GeoLite2-Country.mmdb.gz;gunzip -f /opt/geoip/GeoLite2-Country.mmdb.gz"  >> /var/spool/cron/crontabs/root
    #    service cron restart
    #elif check_sys sysRelease centos; then
    #    ! grep -q "wget http://geolite.maxmind.com" /var/spool/cron/root > /dev/null 2>&1 && echo "01 01 01 * 01 wget http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz -O /opt/geoip/GeoLite2-Country.mmdb.gz;gunzip -f /opt/geoip/GeoLite2-Country.mmdb.gz" >> /var/spool/cron/root
    #    service crond restart
    #fi

}

install_httpguard() {
    local sys_ver=`get_sys_ver`
    mkdir -p /var/log/httpguard/
    if check_sys sysRelease ubuntu;then
        apt-get -y install ipset wget 

    elif check_sys sysRelease centos;then
        yum -y install ipset wget 

    fi

    mkdir -p /var/log/httpguard/
    cd /opt/
    version="v3.1.6"
    tar xf httpguard-$version.tar.gz 
    rm -rf httpguard
    ln -s httpguard-$version httpguard

    cd /opt/httpguard/httpguard/conf
    rm -f captcha.tar.gz
    #if ! wget -t 2 -T 10 http://dl-cn.centos.bz/down/10268950/httpguard/captcha.tar.gz; then
    #    wget -t 2 -T 10 http://dl-us.centos.bz/httpguard/captcha.tar.gz
    #fi
    #wget http://150.109.60.250/captcha.tar.gz    
    #tar xzf captcha.tar.gz
    rm -f captcha.tar.gz
    pid=`ps aux | grep [n]ginx | grep master | awk '{print $2}'`
    if [[ "$pid" != "" ]]; then
        kill $pid
    fi
    sleep 2
    /usr/local/openresty/nginx/sbin/nginx

    mkdir -p /data/nginx/cache
    chmod 777 /data/nginx/cache

    cp /opt/httpguard/agent/nginx.logrotate /etc/logrotate.d/openresty
    chmod 644 /etc/logrotate.d/openresty

    sed -i "s/127.0.0.1/$ip/" /opt/httpguard/agent/td-agent.conf
}

setup_rsyslog() {
    cat > /etc/rsyslog.d/httpguard.conf <<'EOF'
    $ModLoad imudp
    $UDPServerRun 514
    $Umask 0000
    :msg,contains,"[httpguard" /var/log/httpguard.log
    $Umask 0022
    $EscapeControlCharactersOnReceive off
EOF

    service rsyslog restart    
}


close_iptables() {
    local release
    if [[ -f "/etc/redhat-release" ]]; then
        release=`cat /etc/redhat-release | grep -oE [.0-9]+ | awk -F'.' '{print $1}'`
        if [[ $release == "6" ]]; then
            iptables -P INPUT ACCEPT
            iptables -F
        else
            if systemctl stop firewalld.service ;then echo "stop done."; fi
            if systemctl disable firewalld.service ;then echo "disable done."; fi
            
        fi         
    fi
}

start() {
    sed -i "s/MASTER_IPADDR.*/MASTER_IPADDR=\"$ip\"/" /opt/httpguard/agent/config.py

    if [[ "$(ps aux | grep [/]opt/httpguard/master/conf/supervisord.conf)" != "" ]]; then
        if [[ `grep "/opt/httpguard/agent/supervisor_agent.conf" /opt/httpguard/master/conf/supervisord.conf` == "" ]];then 
            sed -i 's#supervisor_master.conf#supervisor_master.conf /opt/httpguard/agent/supervisor_agent.conf#' /opt/httpguard/master/conf/supervisord.conf
        fi
        supervisorctl -c /opt/httpguard/agent/supervisord.conf reload
    else
        cd /opt/httpguard-$version
        rm -rf master
        if [[ -f "/etc/rc.local" ]]; then
            sed -i '/exit 0/d' /etc/rc.local
            if [[ `grep "supervisord.conf" /etc/rc.local` == "" ]];then 
                echo "supervisord -c /opt/httpguard/agent/supervisord.conf" >> /etc/rc.local
            fi 
            chmod +x /etc/rc.local 
        fi
   
        if [[ -f "/etc/rc.d/rc.local" ]]; then
            sed -i '/exit 0/d' /etc/rc.d/rc.local
            if [[ `grep "supervisord.conf" /etc/rc.d/rc.local` == "" ]];then 
                echo "supervisord -c /opt/httpguard/agent/supervisord.conf" >> /etc/rc.d/rc.local
            fi
                       
            chmod +x /etc/rc.d/rc.local 
        fi
        if ! supervisord -c /opt/httpguard/agent/supervisord.conf > /dev/null 2>&1;then
            supervisorctl reload
        fi    
    fi

    # 添加httpguard ipset
    if ! ipset list httpguard > /dev/null 2>&1; then
        ipset -N httpguard iphash maxelem 1000000 timeout 3600
    fi

    # 添加iptables
    if [[ $(iptables -t filter -S INPUT 1 | grep -- '-A INPUT -m set --match-set httpguard src -j DROP') == "" ]];then
        iptables -D INPUT -m set --match-set httpguard src -j DROP >/dev/null 2>&1
        iptables -I INPUT -m set --match-set httpguard src -j DROP
    fi

}

python_version_supoort() {
    local python_ver=`python -V 2>&1| awk -F'[. ]' '{print $2$3}'`
    if [[ $python_ver < 27 ]]; then
        echo "python version must at least python2.7"
        exit 1
    fi
}

sys_version_supoort() {
    if check_sys sysRelease ubuntu;then
        local release=`lsb_release -r | awk '{print $2}'`
        if [[ "$release" != "16.04" ]] && [[ "$release" != "14.04" ]]; then
            echo "only support ubuntu-16.04,ubuntu-14.04 CentOS-6 and CentOS-7"
            exit 1
        fi
    elif check_sys sysRelease centos;then
        local release=`cat /etc/redhat-release | grep -oE [.0-9]+ | awk -F'.' '{print $1}'`
        if [[ "$release" != "7" && "$release" != "6" ]]; then
            echo "only support ubuntu-16.04,ubuntu-14.04, CentOS-7 and CentOS-6"
            exit 1
        fi

    fi    
}

sync_time(){
    echo "start to sync time and add sync command to cronjob..."
    if check_sys sysRelease ubuntu || check_sys sysRelease debian;then
        apt-get -y update
        apt-get -y install ntpdate wget
        /usr/sbin/ntpdate -u pool.ntp.org
        ! grep -q "/usr/sbin/ntpdate -u pool.ntp.org" /var/spool/cron/crontabs/root > /dev/null 2>&1 && echo "*/10 * * * * /usr/sbin/ntpdate -u pool.ntp.org > /dev/null 2>&1;/sbin/hwclock -w"  >> /var/spool/cron/crontabs/root
        service cron restart
    elif check_sys sysRelease centos; then
        yum -y install ntpdate wget
        /usr/sbin/ntpdate -u pool.ntp.org
        ! grep -q "/usr/sbin/ntpdate -u pool.ntp.org" /var/spool/cron/root > /dev/null 2>&1 && echo "*/10 * * * * /usr/sbin/ntpdate -u pool.ntp.org > /dev/null 2>&1;/sbin/hwclock -w" >> /var/spool/cron/root
        service crond restart
    fi
    if /sbin/hwclock -w;then
        return
    fi 
}

install_ac() {
    if check_sys sysRelease ubuntu || check_sys sysRelease debian;then
        apt-get -y install unzip

    elif check_sys sysRelease centos; then
        yum -y install unzip

    fi
    cd /tmp
    wget https://codeload.github.com/cloudflare/lua-aho-corasick/zip/master -O lua-aho-corasick-master.zip
    unzip -u lua-aho-corasick-master.zip
    cd /usr/local/include/
    ln -fs /usr/local/openresty/luajit/include/luajit-2.1/ lua5.1
    cd /tmp/lua-aho-corasick-master
    make
    cp ahocorasick.so /usr/local/openresty/lualib/    
}

install_fluent() {
    if check_sys sysRelease ubuntu || check_sys sysRelease debian;then
        local codename=`lsb_release -c | awk '{print $2}'`
        apt -y install gcc make gnupg2
    elif check_sys sysRelease centos; then
        yum -y install gcc-c++ patch readline readline-devel zlib zlib-devel libyaml-devel libffi-devel openssl-devel make bzip2 autoconf automake libtool bison iconv-devel sqlite-devel make gnupg2

    fi

    #gpg2 --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 || curl -sSL https://rvm.io/mpapis.asc | gpg2 --import -
    gpg2 --keyserver hkp://pool.sks-keyservers.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 7D2BAF1CF37B13E2069D6956105BD0E739499BDB
    curl -L get.rvm.io | bash -s stable
    source /etc/profile.d/rvm.sh
    rvm install 3.0.1
    rvm use 3.0.1
    gem install fluentd
    if [[ ! -f /usr/local/bin/fluentd ]]; then
           ln -s /usr/local/rvm/gems/ruby-3.0.1/wrappers/fluentd /usr/local/bin/fluentd    
    fi
    mkdir -p /var/log/td-agent/
}

ip=$1
if [[ "$ip" == "" ]]; then
    echo "please input ip address."
    exit 1
fi
if [[ ! -f "/opt/httpguard-v3.1.6.tar.gz" ]];then
    echo "please upload httpguard-v3.1.6.tar.gz to /opt"
    exit 1
fi

sys_version_supoort
sync_time
export -f install_fluent
export -f check_sys
bash -c 'install_fluent'
install_python_modules
install_openresty
install_httpguard
setup_rsyslog
close_iptables
install_ac
start
echo "cdnfly installing done."
