#!/bin/bash
set -e

# 1. 要发送的 jar 绝对路径
JAR_FILE="/root/.jenkins/workspace/ruoyi-cloud/ruoyi-modules/xyiot-approval/target/xyiot-modules-approval-3.6.6.jar"

# 2. 远端信息
DST_HOST="192.168.125.2"
SSH_USER="xunyuan"
SSH_PASS="xunyuan@123"
ROOT_PASS="xunyuan@123"
DST_PATH="/home/xunyuan/docker/ruoyi/modules/xyiot-approval/jar"

LOG_FILE="$(dirname "$JAR_FILE")/send-$(date +%F-%H%M%S).log"

log() {
    echo "[$(date '+%F %T')] $*" | tee -a "$LOG_FILE"
}

log "===== 开始发送 $JAR_FILE ====="

# 1) 把 jar 发到远端 /tmp
log "传送 jar 到远端 /tmp ..."
sshpass -p "$SSH_PASS" scp -o StrictHostKeyChecking=no \
  "$JAR_FILE" "$SSH_USER@$DST_HOST:/tmp/xyiot-modules-approval-3.6.6.jar" 2>&1 | tee -a "$LOG_FILE"

# 2) ssh 登录后 su root 并 mv 到最终目录
log "su root 并覆盖目标目录 ..."
sshpass -p "$SSH_PASS" ssh -o StrictHostKeyChecking=no -tt "$SSH_USER@$DST_HOST" <<EOF 2>&1 | tee -a "$LOG_FILE"
expect -c '
    spawn su -c "mv -f /tmp/xyiot-modules-approval-3.6.6.jar $DST_PATH/ && chmod 644 $DST_PATH/xyiot-modules-approval-3.6.6.jar"
    expect "Password:" {send "$ROOT_PASS\r"}
    expect eof
'
exit
EOF

rm -f "$JAR_FILE"

log "✅ 发送完成"
