#!/bin/bash

# ===== 配置区域 =====
MOUNT_DIR="/home/jumpuser/logshttp"
PORT="40070"
# ====================

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
    log {
        output file /var/log/caddy/access.log
    }
}
EOF

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

echo "🔄 重启 Caddy 服务..."
systemctl enable caddy
systemctl restart caddy
sleep 2

echo "🔍 检查 Caddy 状态..."
if systemctl is-active --quiet caddy; then
    echo "✅ Caddy 运行正常"
else
    echo "❌ Caddy 启动失败，查看日志："
    journalctl -u caddy -n 20 --no-pager
    exit 1
fi

echo "🌐 配置防火墙..."
if command -v ufw >/dev/null 2>&1; then
    ufw allow "${PORT}/tcp"
    echo "✅ ufw 已放行端口 $PORT"
fi

# 获取服务器 IP
SERVER_IP=$(curl -s ifconfig.me || hostname -I | awk '{print $1}')

echo ""
echo "=========================================="
echo "✅ 安装完成！"
echo "📁 目录: $MOUNT_DIR"
echo "🌐 访问地址: http://$SERVER_IP:$PORT"
echo ""
echo "⚠️  重要提醒："
echo "   请在云服务商控制台的【安全组】中"
echo "   手动添加入站规则，开放 TCP $PORT 端口"
echo "=========================================="
