#!/usr/bin/env sh
set -euo pipefail

FTP_SYSTEM_USER=${FTP_SYSTEM_USER:-ftpuser}
FTP_SYSTEM_GROUP=${FTP_SYSTEM_GROUP:-ftpgroup}
FTP_ROOT=${PHOTOBOOTH_ROOT:-/photobooth}
FTP_PUBLIC_HOST=${FTP_PUBLIC_HOST:-localhost}
FTP_PORT=${FTP_PORT:-2121}
FTP_PASSIVE_MIN=${FTP_PASSIVE_MIN:-30000}
FTP_PASSIVE_MAX=${FTP_PASSIVE_MAX:-30009}
FTP_MAX_CLIENTS=${FTP_MAX_CLIENTS:-50}
FTP_MAX_PER_IP=${FTP_MAX_PER_IP:-10}
REQUIRE_FTPS=${REQUIRE_FTPS:-0}

# Ensure group/user exist with stable IDs
if command -v getent >/dev/null 2>&1; then
    if ! getent group "${FTP_SYSTEM_GROUP}" >/dev/null 2>&1; then
        addgroup -g 2100 "${FTP_SYSTEM_GROUP}" || true
    fi
else
    addgroup -g 2100 "${FTP_SYSTEM_GROUP}" 2>/dev/null || true
fi

if ! id -u "${FTP_SYSTEM_USER}" >/dev/null 2>&1; then
    adduser -D -H -s /sbin/nologin -G "${FTP_SYSTEM_GROUP}" -u 2100 "${FTP_SYSTEM_USER}" || true
fi

mkdir -p "${FTP_ROOT}" /var/log/pure-ftpd
chown -R "${FTP_SYSTEM_USER}:${FTP_SYSTEM_GROUP}" "${FTP_ROOT}"

FTP_SYSTEM_UID=${FTP_SYSTEM_UID:-$(id -u "${FTP_SYSTEM_USER}")}
FTP_SYSTEM_GID=${FTP_SYSTEM_GID:-$(id -g "${FTP_SYSTEM_USER}")}
export FTP_SYSTEM_UID FTP_SYSTEM_GID FTP_SYSTEM_USER FTP_SYSTEM_GROUP FTP_ROOT

TLS_FLAG="0"
if [ "${REQUIRE_FTPS}" = "1" ] || [ "${REQUIRE_FTPS}" = "true" ]; then
    TLS_FLAG="2"
fi

PURE_FLAGS="-c ${FTP_MAX_CLIENTS} -C ${FTP_MAX_PER_IP} -E -j -R -A -H -B -4 -p ${FTP_PASSIVE_MIN}:${FTP_PASSIVE_MAX} -P ${FTP_PUBLIC_HOST} -u 1000 -Y ${TLS_FLAG} -l puredb:/etc/pure-ftpd/pureftpd.pdb -O w3c:/var/log/pure-ftpd/transfer.log"

echo "[control] Starting pure-ftpd with: ${PURE_FLAGS}"
pure-ftpd ${PURE_FLAGS} &
FTP_PID=$!

echo "[control] Starting control API"
node /app/control-service.js &
API_PID=$!

term_handler() {
    echo "[control] Stopping..."
    kill "${FTP_PID}" "${API_PID}" 2>/dev/null || true
    wait
}

trap term_handler INT TERM

wait
