#!/bin/bash

# ==============================
# 配置部分
# ==============================
CONFIG_FILE="/etc/rsync.conf"

# 默认配置
DEFAULT_SOURCE_DIR="/data/zdir/"
DEFAULT_DEST_USER="root"
DEFAULT_DEST_HOST="43.242.97.55"
DEFAULT_DEST_DIR="/data/zdir/public"
DEFAULT_SSH_PORT=65522
DEFAULT_FEISHU_WEBHOOK="https://open.feishu.cn/open-apis/bot/v2/hook/043360a2-8d08-4295-a7ed-5129a2867363"
DEFAULT_LOG_DIR="/var/log/rsync_logs"
DEFAULT_PID_FILE="/var/run/rsync_fastdfs.pid"
DEFAULT_RSYNC_OPTIONS="-az --partial --compress --compress-level=9 --delete --progress --stats --numeric-ids"

# 加载配置文件
if [ -f "$CONFIG_FILE" ]; then
    source "$CONFIG_FILE"
    # 检查配置项是否为空，如果为空则使用默认值
    SOURCE_DIR=${SOURCE_DIR:-$DEFAULT_SOURCE_DIR}
    DEST_USER=${DEST_USER:-$DEFAULT_DEST_USER}
    DEST_HOST=${DEST_HOST:-$DEFAULT_DEST_HOST}
    DEST_DIR=${DEST_DIR:-$DEFAULT_DEST_DIR}
    SSH_PORT=${SSH_PORT:-$DEFAULT_SSH_PORT}
    FEISHU_WEBHOOK=${FEISHU_WEBHOOK:-$DEFAULT_FEISHU_WEBHOOK}
    LOG_DIR=${LOG_DIR:-$DEFAULT_LOG_DIR}
    PID_FILE=${PID_FILE:-$DEFAULT_PID_FILE}
    RSYNC_OPTIONS=${RSYNC_OPTIONS:-$DEFAULT_RSYNC_OPTIONS}
else
    SOURCE_DIR="$DEFAULT_SOURCE_DIR"
    DEST_USER="$DEFAULT_DEST_USER"
    DEST_HOST="$DEFAULT_DEST_HOST"
    DEST_DIR="$DEFAULT_DEST_DIR"
    SSH_PORT="$DEFAULT_SSH_PORT"
    FEISHU_WEBHOOK="$DEFAULT_FEISHU_WEBHOOK"
    LOG_DIR="$DEFAULT_LOG_DIR"
    PID_FILE="$DEFAULT_PID_FILE"
    RSYNC_OPTIONS="$DEFAULT_RSYNC_OPTIONS"
fi

# 日志文件生成
DATE_FORMAT=$(date '+%Y-%m-%d_%H-%M')
LOG_FILE="$LOG_DIR/rsync_fastdfs_$DATE_FORMAT.log"

# 确保日志目录存在并限制权限
mkdir -p "$LOG_DIR"
chmod 700 "$LOG_DIR"

# 检查日志文件路径是否有效
if [ -z "$LOG_FILE" ]; then
    echo "日志文件路径为空，请检查配置。" >&2
    exit 1
fi

# ==============================
# 依赖检测
# ==============================
check_dependencies() {
    local dependencies=("rsync" "ssh" "curl")
    for cmd in "${dependencies[@]}"; do
        if ! command -v "$cmd" &>/dev/null; then
            echo "缺少依赖: $cmd，请安装后重试。" >&2
            exit 1
        fi
    done
}
check_dependencies

# ==============================
# 日志记录函数
# ==============================
log_message() {
    local level="$1"
    local message="$2"
    local log_line="[$(date '+%Y-%m-%d %H:%M:%S')] [$level] $message"
    echo "$log_line"
    echo "$log_line" >> "$LOG_FILE"
}

# ==============================
# 飞书消息推送函数
# ==============================
send_feishu_message() {
    local status="$1"
    local detail="$2"

    local payload=$(cat <<EOF
{
    "msg_type": "text",
    "content": {
        "text": "FastDFS 文件同步通知：\n状态：$status\n详情：$detail\n时间：$(date '+%Y-%m-%d %H:%M:%S')"
    }
}
EOF
    )
    curl -s -X POST -H "Content-Type: application/json" -d "$payload" "$FEISHU_WEBHOOK" > /dev/null
}

# ==============================
# 同步函数
# ==============================
perform_sync() {
    log_message "INFO" "开始同步 FastDFS 文件"

    # 检查源目录是否存在
    if [ -z "$SOURCE_DIR" ]; then
        log_message "ERROR" "源目录变量未正确设置"
        send_feishu_message "ERROR" "源目录变量未正确设置"
        exit 1
    fi
    if [ ! -d "$SOURCE_DIR" ]; then
        log_message "ERROR" "源目录 $SOURCE_DIR 不存在"
        send_feishu_message "ERROR" "源目录不存在：$SOURCE_DIR"
        exit 1
    fi

    # 检查目标主机的 SSH 可用性
    if [ -z "$DEST_HOST" ] || [ -z "$DEST_USER" ] || [ -z "$SSH_PORT" ]; then
        log_message "ERROR" "目标主机相关配置未正确设置"
        send_feishu_message "ERROR" "目标主机相关配置未正确设置"
        exit 1
    fi
    if ! ssh -p "$SSH_PORT" "$DEST_USER@$DEST_HOST" "exit" 2>/dev/null; then
        log_message "ERROR" "无法连接到目标主机 $DEST_HOST"
        send_feishu_message "ERROR" "目标主机不可达：$DEST_HOST"
        exit 1
    fi

    # 执行同步
    rsync $RSYNC_OPTIONS -e "ssh -p $SSH_PORT" "$SOURCE_DIR" "$DEST_USER@$DEST_HOST:$DEST_DIR" \
        | while read -r line; do
            log_message "DEBUG" "$line"
        done

    local rsync_exit_code=$?
    if [ $rsync_exit_code -eq 0 ]; then
        log_message "INFO" "同步完成"
        send_feishu_message "SUCCESS" "FastDFS 文件同步成功：$SOURCE_DIR -> $DEST_USER@$DEST_HOST:$DEST_DIR"
    else
        log_message "ERROR" "同步失败 (返回码: $rsync_exit_code)"
        send_feishu_message "ERROR" "FastDFS 文件同步失败，请检查日志：$LOG_FILE"
        exit $rsync_exit_code
    fi
}

# ==============================
# 守护进程管理
# ==============================
start_daemon() {
    if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        log_message "ERROR" "守护进程已运行 (PID: $(cat "$PID_FILE"))"
        exit 1
    fi

    # 将所有必要的函数传递给子进程
    nohup bash -c "$(declare -f log_message send_feishu_message perform_sync); perform_sync" > "$LOG_FILE" 2>&1 &
    local pid=$!
    echo "$pid" > "$PID_FILE"
    log_message "INFO" "守护进程已启动 (PID: $pid)"
}

stop_daemon() {
    if [ ! -f "$PID_FILE" ] || ! kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        log_message "ERROR" "守护进程未运行"
        exit 1
    fi

    kill "$(cat "$PID_FILE")"
    if [ $? -eq 0 ]; then
        rm -f "$PID_FILE"
        log_message "INFO" "守护进程已停止"
    else
        log_message "ERROR" "停止守护进程失败"
        exit 1
    fi
}

status_daemon() {
    if [ -f "$PID_FILE" ] && kill -0 "$(cat "$PID_FILE")" 2>/dev/null; then
        log_message "INFO" "守护进程正在运行 (PID: $(cat "$PID_FILE"))"
    else
        log_message "INFO" "守护进程未运行"
    fi
}

clean_logs() {
    log_message "INFO" "清理旧日志"
    find "$LOG_DIR" -type f -mtime +7 -exec rm -f {} \;
    if [ $? -eq 0 ]; then
        log_message "INFO" "日志清理完成"
    else
        log_message "ERROR" "日志清理失败"
        exit 1
    fi
}

# ==============================
# 主程序
# ==============================
case "$1" in
    start)
        start_daemon
        ;;
    stop)
        stop_daemon
        ;;
    restart)
        stop_daemon
        sleep 2
        start_daemon
        ;;
    status)
        status_daemon
        ;;
    clean_logs)
        clean_logs
        ;;
    sync)
        perform_sync
        ;;
    *)
        echo "用法: $0 {start|stop|restart|status|clean_logs|sync}"
        exit 2
        ;;
esac

