#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
TEST_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
PLUGIN_DIR="$(cd "$SCRIPT_DIR/../../client-plugins/all-in-one-full" && pwd)"

# 加载 .env
if [ -f "$TEST_DIR/.env" ]; then
    source "$TEST_DIR/.env"
fi

# 检测容器挂载目录
if docker ps --format '{{.Names}}' | grep -q '^argus-ftp$'; then
    FTP_MOUNT=$(docker inspect argus-ftp --format '{{range .Mounts}}{{if eq .Destination "/private/argus/ftp"}}{{.Source}}{{end}}{{end}}')
    OUTPUT_DIR="${FTP_MOUNT}/share"
    echo "[02] 容器挂载: $OUTPUT_DIR"
else
    OUTPUT_DIR="${DATA_ROOT:-$TEST_DIR/data}/ftp/share"
    echo "[02] 默认路径: $OUTPUT_DIR"
fi

OWNER="${FTP_UID:-2133}:${FTP_GID:-2015}"

cd "$PLUGIN_DIR"

echo "[02] 递增版本号..."
bash scripts/version-manager.sh bump minor

VERSION_FILE="config/VERSION"
if [ ! -f "$VERSION_FILE" ]; then
    echo "[02] 错误: 未找到 $VERSION_FILE"
    exit 1
fi

VERSION=$(cat "$VERSION_FILE" | tr -d '[:space:]')
echo "[02] 新版本: $VERSION"

echo "[02] 构建安装包..."
bash scripts/package_artifact.sh --force

echo "[02] 发布到 FTP: $OUTPUT_DIR"
sudo bash scripts/publish_artifact.sh "$VERSION" --output-dir "$OUTPUT_DIR" --owner "$OWNER"

echo "[02] 设置文件权限..."
# 设置所有者
sudo chown -R "$OWNER" "$OUTPUT_DIR"
# 设置目录权限为 755 (rwxr-xr-x)
sudo find "$OUTPUT_DIR" -type d -exec chmod 755 {} \;
# 设置文件权限为 644 (rw-r--r--)
sudo find "$OUTPUT_DIR" -type f -exec chmod 644 {} \;
# 特别处理 .sh 文件，给予执行权限 755
sudo find "$OUTPUT_DIR" -type f -name "*.sh" -exec chmod 755 {} \;
echo "[02] 权限设置完成 (UID:GID=$OWNER, dirs=755, files=644, scripts=755)"

echo "[02] 发布完成，验证文件..."
ls -lh "$OUTPUT_DIR"

echo "[02] 完成"

