#!/bin/bash

# 使用示例: ./sync_sury.sh php
# 或者: ./sync_sury.sh debian

# 检查参数
if [ $# -lt 1 ]; then
    echo "用法: $0 <仓库名称>"
    echo "例如: $0 php"
    exit 1
fi

REPO_NAME="$1"
SOURCE="rsync://rsync.sury.org/repositories/$REPO_NAME/"
DEST="/opt/mirrors/sury/$REPO_NAME"
LOG_FILE="/var/log/sury_${REPO_NAME}_rsync.log"
LOCK_FILE="/var/lock/sury_${REPO_NAME}_rsync.lock"
RSYNC_OPTS="-avzh --delete --safe-links --timeout=600"

# 日志函数
log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" | tee -a "$LOG_FILE"
}

# 检查锁文件
if [ -e "$LOCK_FILE" ]; then
    if [ -n "$(find "$LOCK_FILE" -mmin +120)" ]; then
        log "发现过期的锁文件 - 强制解锁"
        rm -f "$LOCK_FILE"
    else
        log "同步已在进行中，退出"
        exit 1
    fi
fi

touch "$LOCK_FILE"
mkdir -p "$DEST"

log "开始同步 sury $REPO_NAME 仓库"
rsync $RSYNC_OPTS "$SOURCE" "$DEST" >> "$LOG_FILE" 2>&1
SYNC_RESULT=$?

if [ $SYNC_RESULT -eq 0 ]; then
    log "同步成功完成"
else
    log "同步失败，退出码: $SYNC_RESULT"
fi

echo "Last synced: $(date)" > "$DEST/.last_synced"
rm -f "$LOCK_FILE"

exit $SYNC_RESULT
