#!/bin/bash
# 文件名: rsync_server_install.sh
# Author: Shuhui

# 认证用户
AUTH_USER='www'

# 认证密码
AUTH_PASS='1c790a002393c3e022d50a917a3d26fafedf842'

# 认证文件
AUTH_FILE='/etc/rsyncd.pass'

# Nginx 配置文件目录
RSYNC_DIR='/data/uploads/nginx/'

# 同步模块名称
MOD_NAME='ngx_conf'

# 允许同步的IP(暂时注释)
ALLOW_IP='127.0.0.1'

# 网站根目录
DOCU_ROOT='/data/www/ngx_conf_hash'

function isroot()
{
	if [[ $(id -u) -ne '0' ]] 
	then
		echo 'Please use root role run this script!' && exit -1	
	fi
}

function Install_pkg_7()
{
	rsync --help > /dev/null 2 >&1||yum -y install rsync
        md5deep -h > /dev/null 2 >&1||yum -y install epel-release; yum -y install md5deep
}

function Edit_conf()
{
	# 备份源文件
	[[ -e /etc/rsyncd.conf ]] && \mv /etc/rsyncd.conf /etc/rsyncd.conf.default
	cat > /etc/rsyncd.conf <<EOF
# filename:/etc/rsyncd.conf
	 
#address = 127.0.0.1
port = 873

uid = root
gid = root
 
use chroot = yes
max connections = 10
strict modes = yes
 
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log
 
[${MOD_NAME}]
path = ${RSYNC_DIR}
comment = Rsync Directory
ignore errors
read only = no
write only = no
hosts deny = *
# hosts allow = ${ALLOW_IP}
# hosts allow = *

list = false

# Use Auth
auth users = ${AUTH_USER}
secrets file = ${AUTH_FILE}
EOF
	
	# 生成密码文件并设置权限
	echo "${AUTH_USER}:${AUTH_PASS}" > ${AUTH_FILE}
	chmod 600 ${AUTH_FILE}
}


function RSYNC_SERVICE_7()
{
    # 启动rsyncd
	systemctl restart rsyncd.service
    
    #　开机自动加载rsyncd
	systemctl enable rsyncd.service
}

function Crond() {

if [[ -e /var/spool/cron/root ]]
then
    echo "*/2 * * * * cd ${RSYNC_DIR} && md5deep -r -l ./ssl ./vhosts |sort -k2 > ${DOCU_ROOT}/ngx_conf_md5.txt" >> /var/spool/cron/root
else
    echo "*/2 * * * * cd ${RSYNC_DIR} && md5deep -r -l ./ssl ./vhosts |sort -k2 > ${DOCU_ROOT}/ngx_conf_md5.txt" > /var/spool/cron/root
fi
}

isroot
Install_pkg_7
Edit_conf
RSYNC_SERVICE_7
Crond