#!/bin/bash
set -e

# =======================
# 1️⃣ 清理旧环境
# =======================
echo "[*] 停止 lighttpd 服务（如果存在）..."
systemctl stop lighttpd 2>/dev/null || true
systemctl disable lighttpd 2>/dev/null || true

echo "[*] 卸载 lighttpd 和 apache2-utils（如果安装了）..."
apt-get remove --purge -y lighttpd apache2-utils 2>/dev/null || true
apt-get autoremove -y

echo "[*] 删除残留配置文件和 CGI 脚本..."
rm -f /etc/lighttpd/lighttpd.conf
rm -f /etc/lighttpd/.htpasswd
rm -rf /var/www/html/cgi-bin

echo "[*] 检查端口占用..."
DEFAULT_PORTS=(8081 5004)
for PORTCHK in "${DEFAULT_PORTS[@]}"; do
    PID=$(ss -tlnp | grep ":$PORTCHK " | awk '{print $6}' | cut -d',' -f2)
    if [ -n "$PID" ]; then
        echo "    端口 $PORTCHK 被占用，杀掉进程 $PID"
        kill -9 $PID
    fi
done

echo "[+] 清理完成，环境干净。"

# =======================
# 2️⃣ 交互输入端口和账号（彩色美化）
# =======================
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
RESET="\033[0m"

echo -e "${BLUE}==============================${RESET}"
echo -e "${GREEN}文件管理器安装脚本${RESET}"
echo -e "${BLUE}==============================${RESET}"

read -p "$(echo -e ${YELLOW}请输入访问端口 [默认 8081]:${RESET} )" PORT
PORT=${PORT:-8081}

read -p "$(echo -e ${YELLOW}请输入登录用户名 [默认 admin]:${RESET} )" USER
USER=${USER:-admin}

read -p "$(echo -e ${YELLOW}请输入登录密码 [默认 123456]:${RESET} )" PASS
PASS=${PASS:-123456}

DOCROOT="/var/www/html"
CGIDIR="$DOCROOT/cgi-bin"
CONF="/etc/lighttpd/lighttpd.conf"
PASSFILE="/etc/lighttpd/.htpasswd"

echo "[*] 使用配置:"
echo "    端口: $PORT"
echo "    用户: $USER"
echo "    密码: $PASS"

# =======================
# 3️⃣ 安装依赖
# =======================
if ! command -v lighttpd >/dev/null 2>&1; then
    echo "[*] 安装 lighttpd..."
    apt-get update
    apt-get install -y lighttpd python3
fi

if ! command -v htpasswd >/dev/null 2>&1; then
    echo "[*] 安装 apache2-utils（提供 htpasswd）..."
    apt-get install -y apache2-utils
fi

# =======================
# 4️⃣ 写入 CGI 文件浏览器（美化 UI + UTF-8 保存 + LF + 路径导航 + 自动跳转）
# =======================
mkdir -p "$CGIDIR"
cat > "$CGIDIR/filemgr.py" <<'EOF'
#!/usr/bin/env python3
import cgi, os, sys, urllib.parse

BASE_DIRS = ["/root", "/etc", "/www"]
TEXT_EXT = [".sh", ".py", ".json", ".conf", ".txt", ".log", ".html", ".css", ".js"]

form = cgi.FieldStorage()
path = form.getfirst("path", "")
action = form.getfirst("action", "")

print("Content-Type: text/html; charset=utf-8\n")

def html_header(title="文件管理器"):
    print(f"""<html>
<head>
<meta charset='utf-8'>
<title>{title}</title>
<style>
body {{ font-family: "Segoe UI", Tahoma, sans-serif; background:#f0f2f5; color:#333; padding:10px; }}
h3 {{ background:#4CAF50; color:white; padding:8px; border-radius:4px; }}
a {{ text-decoration:none; color:#007BFF; }}
a:hover {{ text-decoration:underline; }}
ul {{ list-style:none; padding:0; }}
li {{ margin:5px 0; }}
textarea {{ width:100%; height:70vh; font-family: monospace; font-size:14px; padding:5px; border:1px solid #ccc; border-radius:4px; }}
button {{ background:#4CAF50; color:white; border:none; padding:8px 16px; cursor:pointer; margin-top:5px; border-radius:4px; }}
button:hover {{ background:#45a049; }}
.directory {{ font-weight:bold; color:#FF8C00; }}
.file {{ color:#333; }}
.navbar a {{ margin-right:5px; }}
</style>
</head>
<body>""")

def html_footer():
    print("</body></html>")

def safe_path(p):
    p = os.path.abspath(p)
    for b in BASE_DIRS:
        if p.startswith(b):
            return p
    return None

def list_dir(p):
    html_header("目录浏览")
    print(f"<h3>目录: {p}</h3><ul>")
    parent = os.path.dirname(p)
    if safe_path(parent):
        print(f"<li class='directory'><a href='?path={urllib.parse.quote(parent)}'>.. 上级目录</a></li>")
    try:
        for name in sorted(os.listdir(p)):
            full = os.path.join(p, name)
            if os.path.isdir(full):
                print(f"<li class='directory'>[DIR] <a href='?path={urllib.parse.quote(full)}'>{name}</a></li>")
            else:
                print(f"<li class='file'>[FILE] <a href='?path={urllib.parse.quote(full)}'>{name}</a></li>")
    except Exception as e:
        print(f"<p>无法列目录: {e}</p>")
    print("</ul>")
    html_footer()

def edit_file(p):
    dir_path = os.path.dirname(p)
    # 路径导航
    parts = p.strip("/").split("/")
    nav_html = "<div class='navbar'>路径导航: <a href='?path=/'>根目录</a>"
    path_accum = ""
    for part in parts[:-1]:
        path_accum += "/" + part
        nav_html += f" / <a href='?path={urllib.parse.quote(path_accum)}'>{part}</a>"
    nav_html += f" / {parts[-1]}</div>"

    if action == "save":
        data = form.getfirst("content", "")
        try:
            # UTF-8 + LF 保存
            data = data.replace("\r\n", "\n")
            with open(p, "w", encoding="utf-8", newline="\n") as f:
                f.write(data)
            # HTML meta 跳转到所在目录
            html_header("保存成功")
            print(f"<h3>保存成功: {p}</h3>")
            print(f"<meta http-equiv='refresh' content='0; url=?path={urllib.parse.quote(dir_path)}'>")
            html_footer()
        except Exception as e:
            html_header("保存失败")
            print(f"<h3>保存失败: {e}</h3>")
            print(f"<a href='?path={urllib.parse.quote(p)}'>返回编辑</a>")
            html_footer()
        return

    try:
        with open(p, "r", encoding="utf-8") as f:
            content = f.read()
    except Exception as e:
        print(f"<h3>无法读取文件: {e}</h3>")
        return

    html_header("编辑文件")
    print(nav_html)
    print(f"""
    <form method='POST'>
        <input type='hidden' name='path' value='{p}'>
        <input type='hidden' name='action' value='save'>
        <textarea name='content'>{content}</textarea><br>
        <button type='submit'>保存</button>
    </form>
    """)
    html_footer()

# 主逻辑
if not path:
    html_header("文件管理器")
    print("<h3>请选择目录:</h3><ul>")
    for b in BASE_DIRS:
        print(f"<li class='directory'><a href='?path={b}'>{b}</a></li>")
    print("</ul>")
    html_footer()
    sys.exit(0)

real = safe_path(path)
if not real:
    print("<h3>非法路径</h3>")
    sys.exit(0)

if os.path.isdir(real):
    list_dir(real)
else:
    ext = os.path.splitext(real)[1].lower()
    if ext in TEXT_EXT:
        edit_file(real)
    else:
        html_header("文件信息")
        print(f"<h3>无法编辑该文件: {real}</h3>")
        html_footer()
EOF

chmod +x "$CGIDIR/filemgr.py"

# =======================
# 5️⃣ 配置 lighttpd
# =======================
cat > "$CONF" <<EOF
server.modules += ("mod_cgi", "mod_auth")
server.document-root = "$CGIDIR"
index-file.names = ( "filemgr.py" )
cgi.assign = ( ".py" => "/usr/bin/python3" )

auth.backend = "htpasswd"
auth.backend.htpasswd.userfile = "$PASSFILE"
auth.require = ( "" => (
    "method" => "basic",
    "realm" => "Restricted",
    "require" => "valid-user"
))
server.port = $PORT
EOF

# =======================
# 6️⃣ 创建/更新密码文件
# =======================
if [ ! -f "$PASSFILE" ]; then
    htpasswd -b -c "$PASSFILE" "$USER" "$PASS"
else
    htpasswd -b "$PASSFILE" "$USER" "$PASS"
fi

# =======================
# 7️⃣ 启动 lighttpd
# =======================
systemctl restart lighttpd

echo "[+] 文件浏览器部署完成"
echo "访问地址: http://服务器IP:$PORT/"
echo "登录账号: $USER"
echo "登录密码: $PASS"
