#!/bin/bash
# ============================================================
# pure-ftpd 安装与 easypanel 对接
# 原理：pure-ftpd 通过 pure-authd 调用 kangle 的 pureftp_auth
#       认证到 easypanel 的用户库，不使用系统 /etc/passwd
# 用法: bash deploy/ftp-setup.sh
# ============================================================
set -uo pipefail
[ "$(id -u)" = "0" ] || { echo "需要 root"; exit 1; }
PREFIX=/vhs/pure-ftpd
AUTHD_SOCK=/var/run/ftpd.sock
AUTH_BIN=/vhs/kangle/bin/pureftp_auth

grn(){ printf "\033[32m%s\033[0m\n" "$*"; }
step(){ echo; grn "==== $* ===="; }

step "1. 依赖"
if [ -f /etc/debian_version ]; then
  DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential libssl-dev 2>&1 | tail -1
else
  yum -y install gcc gcc-c++ make openssl-devel 2>&1 | tail -1
fi

step "2. 检查纯认证二进制"
if [ ! -x "$AUTH_BIN" ]; then
  cat <<EOF
缺少 $AUTH_BIN —— 这个是 easypanel 自带的认证程序。
它随 kangle/easypanel 包提供，请确认：
  - 面板已完整安装（/vhs/kangle/nodewww/webftp 存在）
  - 该文件从同版本机器复制过来即可
EOF
  exit 1
fi
grn "认证程序就绪"

step "3. 编译安装 pure-ftpd"
VER="${PUREFTP_VER:-1.0.49}"
TMP=$(mktemp -d)
cd "$TMP"
wget -q "https://download.pureftpd.org/pub/pure-ftpd/releases/pure-ftpd-$VER.tar.gz" -O ftp.tgz \
  || { echo "下载失败，可手动放置源码包"; exit 1; }
tar xzf ftp.tgz && cd "pure-ftpd-$VER"
./configure --prefix=$PREFIX CFLAGS=-O2 \
  --with-cookie --with-extauth --with-throttling --with-ratios \
  --with-largefile --with-uploadscript --with-virtualchroot \
  --with-tls > /tmp/pureftpd_conf.log 2>&1 || { echo "configure 失败，见 /tmp/pureftpd_conf.log"; exit 1; }
make -j"$(nproc)" > /tmp/pureftpd_make.log 2>&1 && make install >> /tmp/pureftpd_make.log 2>&1 \
  || { echo "编译失败，见 /tmp/pureftpd_make.log"; exit 1; }
grn "已安装到 $PREFIX"

step "4. 配置"
cat > $PREFIX/etc/pure-ftpd.conf <<'CONF'
ChrootEveryone               yes
BrokenClientsCompatibility   no
MaxClientsNumber             50
Daemonize                    yes
MaxClientsPerIP              8
VerboseLog                   no
DisplayDotFiles              yes
AnonymousOnly                no
NoAnonymous                  yes
SyslogFacility               ftp
DontResolve                  yes
MaxIdleTime                  15
PAMAuthentication            no
UnixAuthentication           no
ExtAuth                      /var/run/ftpd.sock
LimitRecursion               10000 8
MaxLoad                      4
CONF
grn "配置写入 $PREFIX/etc/pure-ftpd.conf"

step "5. 启动 pure-authd（认证代理）"
pkill -f pure-authd 2>/dev/null
"$PREFIX/sbin/pure-authd" --daemonize -s "$AUTHD_SOCK" -r "$AUTH_BIN"
sleep 1
pgrep -c pure-authd >/dev/null && grn "pure-authd 运行中" || { echo "pure-authd 启动失败"; exit 1; }

step "6. 启动 pure-ftpd"
pkill -f "$PREFIX/sbin/pure-ftpd" 2>/dev/null
"$PREFIX/sbin/pure-ftpd" "$PREFIX/etc/pure-ftpd.conf"
sleep 2
ss -lnt 2>/dev/null | grep ':21 ' | head -1

step "7. 开机自启（systemd）"
cat > /etc/systemd/system/pure-authd.service <<EOF
[Unit]
Description=pure-authd for easypanel
After=network.target

[Service]
ExecStart=$PREFIX/sbin/pure-authd -s $AUTHD_SOCK -r $AUTH_BIN
Restart=always

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable pure-authd >/dev/null 2>&1
grn "systemd 单元已创建"

step "完成"
cat <<TIP
验证: ftp://<IP>/ 用面板里的 FTP 账号登录
注意: 若 21 端口未监听，检查 $PREFIX/var/pure-ftpd.log
TIP
