#!/bin/bash
set -euo pipefail

echo "[INFO] Starting FTP server under supervisor..."

FTP_BASE_PATH=${FTP_BASE_PATH:-/private/argus/ftp}
DOMAIN=${DOMAIN:-ftp.metric.argus.com}
FTP_PASSWORD=${FTP_PASSWORD:-ZGClab1234!}

echo "[INFO] FTP base path: ${FTP_BASE_PATH}"
echo "[INFO] Domain: ${DOMAIN}"
echo "[INFO] Setting ftpuser password..."

# 设置ftpuser密码
echo "ftpuser:${FTP_PASSWORD}" | chpasswd

# 确保目录存在
mkdir -p ${FTP_BASE_PATH}/share
mkdir -p /private/argus/etc
mkdir -p /var/run/vsftpd/empty

# 直接使用挂载目录作为FTP根目录，无需软链接
echo "[INFO] Using ${FTP_BASE_PATH}/share as FTP root directory"

# 生成vsftpd配置文件
echo "[INFO] Generating vsftpd.conf with base path: ${FTP_BASE_PATH}"
sed "s|\${FTP_BASE_PATH}|${FTP_BASE_PATH}|g" \
    /etc/vsftpd/vsftpd.conf > /tmp/vsftpd.conf

# 记录容器 IP
IP=$(ifconfig eth0 | awk '/inet /{print $2}' || hostname -i)
echo "current IP: ${IP}"
echo "${IP}" > /private/argus/etc/${DOMAIN}

# 启动vsftpd
echo "[INFO] Starting vsftpd..."
exec /usr/sbin/vsftpd /tmp/vsftpd.conf
