#!/bin/bash

# 检查 root 权限
if [ "$(id -u)" -ne 0 ]; then
    echo "❌ 请用 root 用户运行这个脚本"
    exit 1
fi

# 输入网站根目录
read -p "请输入要作为网站根目录的路径 (例如 /root/qbit/New): " DOCROOT
if [ ! -d "$DOCROOT" ]; then
    echo "❌ 目录不存在: $DOCROOT"
    exit 1
fi

# 输入端口，默认 8080
read -p "请输入端口号 (默认 8080): " PORT
PORT=${PORT:-8080}

# 安装 lighttpd
apt update
apt install -y lighttpd

# 启用目录列表模块
lighty-enable-mod dir-listing 2>/dev/null

# 写配置
CONFIG_FILE="/etc/lighttpd/lighttpd.conf"
cat > "$CONFIG_FILE" <<EOF
server.document-root = "$DOCROOT"
server.port = $PORT

# 启用目录浏览
dir-listing.activate = "enable"
dir-listing.hide-dotfiles = "enable"

# 设置目录浏览编码为 UTF-8
dir-listing.encoding = "utf-8"
server.modules += ( "mod_setenv" )
setenv.add-response-header = ( "Content-Type" => "text/html; charset=utf-8" )

# 常见文件类型 MIME 设置（加上 UTF-8 编码）
mimetype.assign = (
    ".html" => "text/html; charset=utf-8",
    ".txt"  => "text/plain; charset=utf-8",
    ".log"  => "text/plain; charset=utf-8",
    ".jpg"  => "image/jpeg",
    ".jpeg" => "image/jpeg",
    ".png"  => "image/png",
    ".gif"  => "image/gif",
    ".mp4"  => "video/mp4",
    ".webm" => "video/webm",
    ".ogg"  => "video/ogg",
    ".mp3"  => "audio/mpeg",
    ".pdf"  => "application/pdf"
)
EOF

# 重启服务
systemctl enable lighttpd
systemctl restart lighttpd

IP=$(hostname -I | awk '{print $1}')
echo "✅ 部署完成！"
echo "📂 网站根目录: $DOCROOT"
echo "🌐 请在浏览器访问: http://$IP:$PORT"
