#!/usr/bin/env bash
# entrypoint.sh — configure a chrooted SFTP-only user and start sshd + Apache.
# The user lands in /uploads (its only writable dir); Apache publishes that same
# /uploads dir as the HTTP DocumentRoot root, so a file afaq uploads to the
# relative path "foo/bar.jpg" is fetchable at http://sftp/foo/bar.jpg.
# Runs as root.
set -e

SFTP_USER="${SFTP_USER:-afaq_ftp_user}"
SFTP_PASS="${SFTP_PASS:-afaq_ftp_pwd}"
SFTP_GROUP="sftpusers"
SFTP_ROOT="/srv/sftp"
WEB_ROOT="${SFTP_ROOT}/data"          # chroot root (must be root-owned)
UPLOAD_DIR="uploads"                  # writable landing dir == Apache DocumentRoot
UPLOAD_PATH="${WEB_ROOT}/${UPLOAD_DIR}"
SSL_DIR="/etc/ssl/sftp-http"

echo "[sftp] configuring user '${SFTP_USER}'"

# --- Group + user (SFTP-only: nologin shell) -------------------------------
getent group "$SFTP_GROUP" >/dev/null || groupadd "$SFTP_GROUP"
if ! id -u "$SFTP_USER" >/dev/null 2>&1; then
    useradd -d "$WEB_ROOT" -s /usr/sbin/nologin -g "$SFTP_GROUP" "$SFTP_USER"
else
    usermod -d "$WEB_ROOT" -s /usr/sbin/nologin -g "$SFTP_GROUP" "$SFTP_USER"
fi
echo "${SFTP_USER}:${SFTP_PASS}" | chpasswd

# --- Chroot dirs: every path component must be root-owned + not group/other-writable
mkdir -p "$WEB_ROOT"
chown root:root "$SFTP_ROOT" "$WEB_ROOT"
chmod 755       "$SFTP_ROOT" "$WEB_ROOT"

# --- Writable upload dir, owned by the SFTP user (Apache www-data can read it) -
mkdir -p "$UPLOAD_PATH"
chown -R "${SFTP_USER}:${SFTP_GROUP}" "$UPLOAD_PATH"
find "$UPLOAD_PATH" -type d -exec chmod 755 {} +

# --- sshd drop-in: SFTP-only, chrooted, lands the user in /uploads ----------
mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/sftp.conf <<EOF
# Managed by the sftp container entrypoint — SFTP-only access for ${SFTP_USER}.
Subsystem sftp internal-sftp

Match User ${SFTP_USER}
    ChrootDirectory %h
    # -u 0022 => new files land 0644, new dirs 0755, so Apache can read uploads.
    ForceCommand internal-sftp -d /${UPLOAD_DIR} -u 0022
    AllowTcpForwarding no
    X11Forwarding no
    PasswordAuthentication yes
    PermitTunnel no
EOF
# Ubuntu's stock sshd_config also declares Subsystem sftp — comment it out so
# our internal-sftp wins.
sed -i -E 's|^([[:space:]]*Subsystem[[:space:]]+sftp.*)$|# \1|' /etc/ssh/sshd_config || true

# --- HTTPS self-signed cert ------------------------------------------------
if [ ! -f "${SSL_DIR}/selfsigned.crt" ] || [ ! -f "${SSL_DIR}/selfsigned.key" ]; then
    echo "[sftp] generating self-signed TLS certificate"
    mkdir -p "$SSL_DIR"
    openssl req -x509 -nodes -newkey rsa:2048 -days 3650 \
        -keyout "${SSL_DIR}/selfsigned.key" \
        -out    "${SSL_DIR}/selfsigned.crt" \
        -subj "/CN=sftp" -addext "subjectAltName=DNS:sftp,DNS:localhost" >/dev/null 2>&1 || \
        echo "[sftp] WARN: cert generation failed — HTTPS vhost may not start"
    chmod 600 "${SSL_DIR}/selfsigned.key" 2>/dev/null || true
    chmod 644 "${SSL_DIR}/selfsigned.crt" 2>/dev/null || true
fi

# --- Validate sshd config + launch sshd (background) and Apache (foreground) -
mkdir -p /var/run/sshd
ssh-keygen -A >/dev/null 2>&1 || true
sshd -t
echo "[sftp] sshd ready — user=${SFTP_USER}, chroot=${WEB_ROOT}, lands in /${UPLOAD_DIR}"
/usr/sbin/sshd

# shellcheck disable=SC1091
. /etc/apache2/envvars
mkdir -p "$APACHE_RUN_DIR" "$APACHE_LOCK_DIR" "$APACHE_LOG_DIR"
rm -f "$APACHE_PID_FILE"
echo "[sftp] starting Apache (serving /${UPLOAD_DIR} at the HTTP root)"
exec apache2ctl -D FOREGROUND
