#!/bin/bash

# 配置参数
HOSTNAME="36.103.203.5"
USERNAME="deployqh1@BSCC-QH1"
PASSWORD="tH64y82wVUmiQ1YNMOuqep3c5bz097Xo"  # 注意：在生产环境中应使用SSH密钥而不是密码
LOG_PATH="/publica/home/deployqh1/run_test/log"
SUCCESS_PATTERN="successful"
REMOTE_DATA_PATH="/publica/home/deployqh1/run_test/USGS-gtopo30_0.9x1.25_remap_c051027.nc"
LOCAL_DESTINATION="USGS-gtopo30_0.9x1.25_remap_c051027.nc"
MAX_ATTEMPTS=10
WAIT_SECONDS=10

# 检查日志中的成功标志
check_log() {
    echo "正在检查日志文件..."
    attempt=1
    while [ $attempt -le $MAX_ATTEMPTS ]; do
        # 使用SSH读取日志的最后100行
        log_content=$(sshpass -p "$PASSWORD" ssh -o StrictHostKeyChecking=no $USERNAME@$HOSTNAME "tail -100 $LOG_PATH" 2>/dev/null)
        
        if echo "$log_content" | grep -q "$SUCCESS_PATTERN"; then
            echo "找到成功标志!"
            return 0
        else
            echo "未找到成功标志，等待$WAIT_SECONDS秒后重试... ($attempt/$MAX_ATTEMPTS)"
            sleep $WAIT_SECONDS
            attempt=$((attempt+1))
        fi
    done
    
    echo "错误: 在最大尝试次数内未找到成功标志"
    return 1
}
# 拉取远程数据
transfer_data() {
    echo "正在从远程服务器拉取数据..."
    
    # 使用scp复制文件
    if sshpass -p "$PASSWORD" scp -o StrictHostKeyChecking=no $USERNAME@$HOSTNAME:"$REMOTE_DATA_PATH" "$LOCAL_DESTINATION"; then
        echo "数据传输完成!"
        return 0
    else
        echo "数据传输失败!"
        return 1
    fi
}

# 主执行逻辑
if check_log; then
    if transfer_data; then
        echo "操作成功完成!"
        exit 0
    else
        echo "数据传输失败!"
        exit 1
    fi
else
    echo "未找到成功标志，操作中止!"
    exit 1
fi
