#!/bin/bash

# ===== 配置区域 =====
MOUNT_DIR="/home/jumpuser/logshttp"   # 要挂载的目录，请改成你自己的
PORT="40070"                   # 监听端口
# ====================

# 确保脚本以 root 权限运行
if [[ $EUID -ne 0 ]]; then
   echo "❌ 请用 sudo 运行: sudo $0"
   exit 1
fi

echo "🔍 检查 Caddy 是否安装..."
if ! command -v caddy >/dev/null 2>&1; then
    echo "📥 未检测到 Caddy，开始安装..."
    apt update
    apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' \
        | gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' \
        | tee /etc/apt/sources.list.d/caddy-stable.list
    apt update
    apt install -y caddy
else
    echo "✅ 检测到 Caddy 已安装"
fi

echo "📂 创建挂载目录: $MOUNT_DIR"
mkdir -p "$MOUNT_DIR"

echo "📝 生成 Caddy 配置文件..."
cat > /etc/caddy/Caddyfile <<EOF
:$PORT {
    root * $MOUNT_DIR
    file_server browse
}
EOF

echo "🔐 调整目录权限..."
chown -R caddy:caddy "$MOUNT_DIR"
chmod -R 755 "$MOUNT_DIR"

echo "🔄 重新加载 Caddy..."
systemctl restart caddy

echo "🌐 开放防火墙端口 $PORT..."
if command -v ufw >/dev/null 2>&1; then
    ufw allow "${PORT}/tcp" || true
else
    echo "⚠ 未检测到 ufw，请在云控制台安全组手动放行 $PORT 端口"
fi

echo "✅ 完成！现在可以访问: http://你的服务器IP:$PORT"
