#!/bin/bash

set -o errexit

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

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

    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_mysql() {
    if mysql -uroot -proot -e 'select 1';then
        return 0
    fi

    if check_sys sysRelease ubuntu;then
        export DEBIAN_FRONTEND="noninteractive"
        debconf-set-selections <<< "mariadb-server mysql-server/root_password password root"
        debconf-set-selections <<< "mariadb-server mysql-server/root_password_again password root"         
        apt-get update
        apt-get install -y mariadb-server
        systemctl start mysql
        systemctl enable mysql        
    elif check_sys sysRelease centos;then
        local release=`cat /etc/redhat-release | grep -oE [.0-9]+ | awk -F'.' '{print $1}'`
        if [[ $release == "7" ]]; then
            yum install -y mariadb-server
            if [[ `grep max_allowed_packet /etc/my.cnf` == "" ]];then
                sed -i '/\[mysqld\]/amax_allowed_packet=10M' /etc/my.cnf
            fi    
            systemctl start mariadb
            systemctl enable mariadb
        fi

        if [[ $release == "6" ]]; then
            yum -y remove mysql-libs.x86_64
            wget dev.mysql.com/get/mysql-community-release-el6-5.noarch.rpm
            yum localinstall -y mysql-community-release-el6-5.noarch.rpm
            yum install -y mysql-community-server
            if [[ `grep max_allowed_packet /etc/my.cnf` == "" ]];then
                sed -i '/\[mysqld\]/amax_allowed_packet=10M' /etc/my.cnf
            fi
            chkconfig mysqld on
            service mysqld start            
        fi    

    fi        

    /usr/bin/mysqladmin -u root password 'root'
    mysql -uroot -proot -e "CREATE DATABASE guard CHARSET=UTF8;"
    mysql -uroot -proot -e 'grant all privileges on *.* to "root"@"127.0.0.1" identified by "root"'
}

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 libmysqlclient-dev libffi-dev libssl-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 mariadb-devel libffi-devel
        else
            install_python27
            yum -y --enablerepo=epel install gcc mysql-community-devel libffi-devel nss
        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
    $pip install MySQL-python
    $pip install Flask==0.12.2
    $pip install requests
    $pip install flask_sqlalchemy==2.2
    $pip install timeout_decorator
    $pip install pycrypto
    $pip install supervisor
    $pip install --upgrade setuptools
    $pip install cffi
    $pip install cryptography
    $pip install enum34
    $pip install ipaddress 
    $pip install restclient
    $pip install CloudXNS-API-SDK-Python
    $pip install python-dateutil
    $pip install dnspython
    $pip install pyopenssl
    $pip install apscheduler
    $pip install pycryptodome
}

install_httpguard() {
    local sys_ver=`get_sys_ver`
    if check_sys sysRelease ubuntu;then
        apt-get -y install  wget 

    elif check_sys sysRelease centos;then
        yum -y install  wget 

    fi    
    mkdir -p /var/log/httpguard/
    cd /opt/
    version="v3.1.6"
    tar xf httpguard-$version.tar.gz 
    rm -f httpguard
    ln -s httpguard-$version httpguard
    rand=`cat /dev/urandom | head -n 10 | md5sum | head -c 16`
    sed -i "s/KEY.*/KEY='$rand'/"  /opt/httpguard/master/conf/config.py
}

init_db() {
    export HTTPGUARD_SETTINGS=/opt/httpguard/master/conf/config.py
    cd /opt/httpguard/master
    if python init_table.py;then
        return 0
    fi    
}

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
            systemctl stop firewalld.service
            systemctl disable firewalld.service 
        fi         
    fi
}

install_acme(){
    if check_sys sysRelease ubuntu;then
        apt install -y socat

    elif check_sys sysRelease centos;then
        yum -y install  socat crontabs nss curl libcurl
    fi       
    curl https://get.acme.sh | sh
    
    /root/.acme.sh/acme.sh --uninstall-cronjob
}

start() {
    if [[ "$(ps aux | grep [/]opt/httpguard/agent/supervisord.conf)" != "" ]]; then
        if [[ `grep "/opt/httpguard/master/conf/supervisor_master.conf" /opt/httpguard/agent/supervisord.conf` == "" ]];then 
            sed -i 's#supervisor_agent.conf#supervisor_agent.conf /opt/httpguard/master/conf/supervisor_master.conf#' /opt/httpguard/agent/supervisord.conf
        fi
        supervisorctl -c /opt/httpguard/master/conf/supervisord.conf reload
    else
        cd /opt/httpguard/
        rm -rf agent httpguard
        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/master/conf/supervisord.conf" >> /etc/rc.local
            fi 
            chmod +x /etc/rc.local
        fi
  

        if [[ -f "/etc/rc.d/rc.local" ]]; then
            if [[ `grep "supervisord.conf" /etc/rc.d/rc.local` == "" ]];then 
                echo "supervisord -c /opt/httpguard/master/conf/supervisord.conf" >> /etc/rc.d/rc.local
            fi 
            chmod +x /etc/rc.d/rc.local 
        fi
        supervisord -c /opt/httpguard/master/conf/supervisord.conf    
    fi

    # 获取授权
    cd /opt/httpguard/master;python2.7 -c "import auth;auth.fetch_remote_auth()" 
    
}

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}'`
        local codename=`lsb_release -c | awk '{print $2}'`
        if [[ "$release" != "16.04" ]] && [[ "$release" != "14.04" ]]; then
            echo "only support ubuntu-16.04,ubuntu-14.04 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 make
        /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 make vixie-cron
        /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_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 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 2.4.1
    rvm use 2.4.1
    gem install fluentd
    gem install fluent-plugin-mysql
    if [[ ! -f /usr/local/bin/fluentd ]]; then
           ln -s /usr/local/rvm/gems/ruby-2.4.1/wrappers/fluentd /usr/local/bin/fluentd
    fi
    mkdir -p /var/log/td-agent/

}


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`
}

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
install_mysql
install_python_modules
install_httpguard
close_iptables
init_db
install_acme
export -f install_fluent
export -f check_sys
bash -c 'install_fluent'
start
echo "cdnfly installing done."
