#!/bin/bash
# 文件名: rsync_server.sh

### 变量定义 开始

# rsync 运行用户属主
readonly RSYNC_OWNER='rsync'

# 认证用户
readonly RSYNC_AUTH_USER='gitee'

# rsync 服务监听的端口
readonly RSYNC_PORT='873'

# 认证密码
readonly RSYNC_AUTH_PASSWORD='790a002393c3e022d50a917a3d26fafedf842'

# 认证文件
readonly RSYNC_AUTH_FILE='/etc/rsyncd_users.db'

# 允许访问的IP
readonly ALLOW_IP='127.0.0.1'

# rsync 模块名称
readonly RSYNC_MODULE_NAME='CHANGEME'

# 备份目录
readonly DATA_ROOT='/data/xxxx'

### 变量定义 结束

rsync --help > /dev/null 2 >&1 || echo "[ rsync] 工具不存在,请检查!"; exit 67

cat > /etc/rsyncd.conf <<EOF
# 文件名:/etc/rsyncd.conf
	 
#address = 127.0.0.1
port = ${RSYNC_PORT}

uid = root
gid = root
 
#fake super = yes
list = false 
use chroot = yes
max connections = 10
strict modes = yes
exclude = lost+found/
log file = /var/log/rsyncd.log
lock file = /var/run/rsyncd.lock
pid file = /var/run/rsyncd.pid
 
[${RSYNC_MODULE_NAME}]
    path = ${DATA_ROOT}
    comment = Rsync Directory
    read only = yes
    write only = no
    hosts allow = ${ALLOW_IP}
    dont compress = *.gz *.bz2 *.zip *.zst
    hosts deny = *
    auth users = ${RSYNC_AUTH_USER}
    secrets file = ${RSYNC_AUTH_FILE}
EOF

# 生成密码文件并设置权限
echo "${RSYNC_AUTH_USER}:${RSYNC_AUTH_PASSWORD}" | tee ${RSYNC_AUTH_FILE}
chmod 600 ${RSYNC_AUTH_FILE}


# 启动rsyncd
systemctl restart rsyncd.service

# 开机自动加载rsyncd
systemctl enable rsyncd.service

