#!/bin/sh

function CreatePath()
{
    local path_= mod_=
    
    ShowResult "[green]正在创建路径...[/green]" 1
    
    for i in ${!_MKDIR_[*]}; do
        if [ -z "${_MKDIR_[${i}]}" ]; then continue; fi
        mod_=
        if [ `echo "${_MKDIR_[${i}]}" | grep -c ','` -gt 0 ]; then
            path_=`echo "${_MKDIR_[${i}]}" | cut -d, -f1`
            mod_=`echo "${_MKDIR_[${i}]}" | cut -d, -f2`
        else
            path_="${_MKDIR_[${i}]}"
        fi
        
        mkdir -p "${path_}"
        
        if [ ! -z "${mod_}" ]; then
            chmod ${mod_} -R "${path_}"
        fi
    done
    
    ShowStatus $?
}

# functions - prepare for installation
# @function prepare
function Prepare()
{
    local host_=
    
    clear
    echo "服务器安装系统正在初始化... 请稍候..."
    
    for i in ${!_HOSTS_[*]}; do
        eval declare -A host_=${_HOSTS_[$i]} 2>/dev/null
        [ -z "${host_[*]}" ] && continue
        # add repo server if not exists in hosts-files
        if [ `cat ${_PATH_HOSTS_} | grep -e "\b${host_[name]}\b" | wc -l` -eq 0 ]
        then
            echo -e "${host_[ip]}\t${host_[name]}" >> ${_PATH_HOSTS_}
        fi
    done
    
    # install perl if not exists
    which perl > /dev/null 2>&1
    local _errid=$?
    if [ ${_errid} -gt 0 ]
    then
        eval yum install perl -y ${_SYS_SHOW_INSTALL_DETAILS_}
    fi
    
    clear
}

# functions - checker
# @function Check Install
function CheckInstall()
{
    local msg="[green]确定要安装服务器吗?(Y/n)[/green]:"
    
    if [ -f ${_PATH_INIT_LCK_} ]; then
        GetInstallStep
        msg="[green]确定要**继续安装**服务器吗?当前进行到(Step:${_INSTALL_STEP_})(Y/n)[/green]:"
    fi
    
    ShowResult ${msg} 1
    read isinstall_
    echo
    
    if [ ${isinstall_//[Yy]/y} != "y" ]; then
        ShowResult "[yellow]已退出安装, BYE~[/yellow]"
        exit
    fi
    
    ShowResult "开始安装服务器..."
    
    if [ ! -f ${_PATH_INIT_LCK_} ]; then
        # lock
        touch ${_PATH_INIT_LCK_}
        # clear log
        rm -rf ${_PATH_INIT_LCK_} > /dev/null 2>&1
    fi
}

# @function Check Reboot
function CheckReboot()
{
    ShowResult "[green]确定要重新启动服务器吗?(Y/n)[/green]"
    read isreboot_
    
    if [ "${isreboot_//[Yy]/y}" = "y" ]; then
        reboot
        exit
    fi
}

# @function get software
function GetSoftware()
{
    # download from remote server
    if [ ${_IS_GET_SOFTWARE_} -eq 1 ]
    then
        ShowResult "[green]正在下载所需软件... [/green]" 1
        cd ${_PATH_SOFTWARE_}
        eval wget -c -r -nd -np -k -L -p "http://`GetInfo "${_HOSTS_[SOFTWARE]}" name`/${_SOFTWARE_NAME_:-${_INSTALL_SH_NAME_:-${_GAME_NAME_}}}/" ${_SYS_SHOW_INSTALL_DETAILS_}
        ShowStatus $?
    fi
}

# @function get configuration files from svn
function GetConfiguration()
{
    ShowResult "[green]正在下载系统配置文件... [/green]" 1
    
    # co configs
    if [ $(echo "${_SVN_[CONF_PATH]}" | grep -c "^svn://") -eq 0 ]; then
        eval svn export ${_SVN_[HOST_FULLPATH]}${_SVN_[CONF_PATH]} ${_PATH_CONFIGS_} ${_SVN_CMD_EXT_[EXPORT]} ${_SYS_SHOW_INSTALL_DETAILS_}
    else
        eval svn export ${_SVN_[CONF_PATH]} ${_PATH_CONFIGS_} ${_SVN_CMD_EXT_[EXPORT]} ${_SYS_SHOW_INSTALL_DETAILS_}
    fi
    ShowStatus $?
}

# @function get maintainace-tool files from svn
function GetMaintainaceTools()
{
    ShowResult "[green]正在下载运维工具文件... [/green]" 1
    
    # co configs
    if [ $(echo "${_SVN_[CONF_PATH]}" | grep -c "^svn://") -eq 0 ]; then
        eval svn co ${_SVN_[HOST_FULLPATH]}${_SVN_[CMD_PATH]} ${_PATH_CMD_} ${_SVN_CMD_EXT_[CO]} ${_SYS_SHOW_INSTALL_DETAILS_}
    else
        eval svn co ${_SVN_[CMD_PATH]} ${_PATH_CMD_} ${_SVN_CMD_EXT_[CO]} ${_SYS_SHOW_INSTALL_DETAILS_}
    fi
    chmod +x -R ${_PATH_CMD_}
    ShowStatus $?
}

# function - system update
# @function upgrade system
function UpdateSystem()
{
    ShowResult "[green]正在升级操作系统... [/green]" 1
    
    eval yum clean all ${_SYS_SHOW_INSTALL_DETAILS_}
    ShowStatus $? 1
    
    # update basic
    if [ ${_IS_UPDATE_FIRST_} -eq 1 ]
    then
        eval yum update -y --skip-broken ${_SYS_SHOW_INSTALL_DETAILS_}
        ShowStatus $? 1
    fi
    
    # install other softwares
    eval yum install flex bison autoconf automake bzip2-devel zlib-devel ncurses-devel tmpwatch \
        curl curl-devel libtool zip unzip pam-devel openssl-devel libxml2-devel gdb bzip2 vixie-cron \
        crontabs bash subversion cmake libstdc++44-devel vim ntp readline-devel make wget gcc gcc-c++ \
        lynx tree telnet file nc python-devel pcre-devel glib2-devel ${_GAME_EXT_YUM_PACKAGES_} \
        -y --skip-broken ${_SYS_SHOW_INSTALL_DETAILS_}
    
    ShowStatus $? 1
    
    # modify default charsets
    echo "LANG=\"en_US.UTF-8\"" > /etc/sysconfig/i18n
    source /etc/sysconfig/i18n
    
    ShowStatus $? 1
    
    # allow subversion to save data (user&pass)
    eval svn info ${_SYS_SHOW_INSTALL_DETAILS_}
    eval rm -rf ~/.subversion/auth/svn.simple/* ${_SYS_SHOW_INSTALL_DETAILS_}
    sed -ri '$astore-passwords = yes\nstore-plaintext-passwords = yes' ~/.subversion/servers
    
    ShowStatus $?
}

# @function link liberary files
function LinkLiberaryFiles()
{
    ShowResult "[green]正在链接动态库... [/green]" 1

    eval ln -s /usr/local/lib/* /usr/lib/ ${_SYS_SHOW_INSTALL_DETAILS_}
    eval ldconfig ${_SYS_SHOW_INSTALL_DETAILS_}
    
    ShowStatus $?
}

# @function performace system
function PerformanceSystem()
{
    local php_= cpp_=
    
    ShowResult "[green]正在优化系统性能... [/green]" 1
    
    if [ ! -z "${_HOSTS_[PHP]}" ]; then
        eval declare -A php_="${_HOSTS_[PHP]}"
    fi
    if [ ! -z "${_HOSTS_[CPP]}" ]; then
        eval declare -A cpp_="${_HOSTS_[CPP]}"
    fi
    
    # backup first
    eval \cp -f /etc/sysctl.conf ${_PATH_BACKUP_} ${_SYS_SHOW_INSTALL_DETAILS_}
    eval \cp -f /etc/security/limits.conf ${_PATH_BACKUP_} ${_SYS_SHOW_INSTALL_DETAILS_}
    
    # update
    eval \cp -f ${_PATH_CONFIGS_}/sysctl.conf /etc/sysctl.conf ${_SYS_SHOW_INSTALL_DETAILS_}
    echo -e '\n* soft nofile 1048576\n* hard nofile 1048576' >> /etc/security/limits.conf
    eval ulimit -HSn 1048576 ${_SYS_SHOW_INSTALL_DETAILS_}
    
    # reset
    eval sysctl -p ${_SYS_SHOW_INSTALL_DETAILS_}
    
    # add php-server-name to php-server-ip if not in hosts
    if [ ! -z "${php_[*]}" ] && [ `cat ${_PATH_HOSTS_} | grep -e "\b${php_[name]}\b" | wc -l` -eq 0 ]
    then
        echo -e "${php_[ip]}\t${php_[name]}" >> ${_PATH_HOSTS_}
    fi
    
    # add cpp-server-name to cpp-server-ip if not in hosts
    if [ ! -z "${cpp_[*]}" ] && [ `cat ${_PATH_HOSTS_} | grep -e "\b${cpp_[name]}\b" | wc -l` -eq 0 ]
    then
        echo -e "${cpp_[ip]}\t${cpp_[name]}" >> ${_PATH_HOSTS_}
    fi
    
    # change hostname
    hostname ${_SERVER_NAME_}
    sed -ri 's#(HOSTNAME=)(.*)#\1'"${_SERVER_NAME_}"'#' /etc/sysconfig/network
    # add host-name to 127.0.0.1 if not in hosts
    if [ `cat ${_PATH_HOSTS_} | grep -e "\b${_SERVER_NAME_}\b" | wc -l` -eq 0 ]
    then
        echo -e "127.0.0.1\t${_SERVER_NAME_}" >> ${_PATH_HOSTS_}
    fi
    
    # set path
    cat >> /etc/profile <<EOF

export PATH=/usr/local/mysql/bin:/usr/local/php/bin:\$PATH
EOF
    . /etc/profile
    
    # set timezone
    if [ "$(cat /usr/share/zoneinfo/${_TIMEZONE_})" != "$(cat /etc/localtime)" ]; then
        eval \cp -f /usr/share/zoneinfo/${_TIMEZONE_} /etc/localtime ${_SYS_SHOW_INSTALL_DETAILS_}
    fi
    
    ShowStatus $?
}

# @function create crond@root
function CreateCrond()
{
    local src_="${_PATH_CONFIGS_}/crond-multi"

    if [ ! -f "${src_}" ]; then
        return
    fi

    ShowResult "[green]正在创建计划任务...[/green]" 1
    
    # check if already insert
    if [[ ! -f ${_PATH_CRON_} ]] || [[ `cat ${_PATH_CRON_} 2> /dev/null | grep -c ${_SIGNATURE_}` -eq 0 ]]
    then
        # enhance
        cat ${src_} >> ${_PATH_CRON_}
    fi
    
    # change patterns
    sed -ri "
        s@\{Signature\}@${_SIGNATURE_}@;
        s@\{cmdpath\}@${_PATH_CMD_}@;
        " ${_PATH_CRON_}
    
    ShowStatus $?
}

# @function add iptable ports
function EditPortsToIptables()
{
    local args_= iptcnt_=0 iptmode_= rule_=
    
    ShowResult "[green]正在进行防火墙设置...[/green]" 1
    
    # check if iptables exists
    if [ ! -z "$(chkconfig --list iptables 2>/dev/null)" ]; then
        /sbin/service iptables save
        # clear iptables' cache
        /sbin/service iptables restart
        
        # accept ports
        for i in ${!_IPTABLES_[*]}; do
            rule_=${_IPTABLES_[$i]}
            if [ -z "${rule_}" ]; then continue; fi
            iptcnt_=`/sbin/iptables -S INPUT | grep -v ^-P | wc -l`
            iptmode_=" -A INPUT "
            args_=`echo ${rule_} | awk -F';' '{
                printf("%s%s%s%s", 
                        $1 != "" ? $1 : " -m state --state NEW ", 
                        $3 != "" ? " -p "$3" -m "$3 : ($2 != "" ? " -m tcp -p tcp " : ""), 
                        $2 != "" ? " --dport "$2 : "",
                        $4 != "" ? " -j "$4 : " -j ACCEPT ")
                }'`
            if [ ${iptcnt_} -gt 1 ]; then iptmode_=" -I INPUT ${iptcnt_} "; fi
            eval /sbin/iptables ${iptmode_} ${args_} ${_SYS_SHOW_INSTALL_DETAILS_}
        done
        # save & restart iptables
        /sbin/service iptables save
        /sbin/service iptables restart
    fi
    
    ShowStatus $?
}