#!/bin/sh
set -e

SSH_USER="${SSH_USER:-player}"
SSH_PASSWORD="${SSH_PASSWORD:-player}"

if ! id -u "$SSH_USER" >/dev/null 2>&1; then
    adduser --disabled-password --gecos "" "$SSH_USER"
fi

echo "$SSH_USER:$SSH_PASSWORD" | chpasswd
chown -R "$SSH_USER":"$SSH_USER" /app/proxy

SSH_KEYS_DIR="/app/proxy/ssh-host-keys"
mkdir -p "$SSH_KEYS_DIR"
chmod 700 "$SSH_KEYS_DIR"
if [ ! -f "$SSH_KEYS_DIR/ssh_host_ecdsa_key" ]; then
    ssh-keygen -t ecdsa -b 521 -N "" -f "$SSH_KEYS_DIR/ssh_host_ecdsa_key" >/dev/null
fi
if [ ! -f "$SSH_KEYS_DIR/ssh_host_ed25519_key" ]; then
    ssh-keygen -t ed25519 -N "" -f "$SSH_KEYS_DIR/ssh_host_ed25519_key" >/dev/null
fi
chown root:root \
    "$SSH_KEYS_DIR/ssh_host_ecdsa_key" "$SSH_KEYS_DIR/ssh_host_ecdsa_key.pub" \
    "$SSH_KEYS_DIR/ssh_host_ed25519_key" "$SSH_KEYS_DIR/ssh_host_ed25519_key.pub"
chmod 600 "$SSH_KEYS_DIR/ssh_host_ecdsa_key" "$SSH_KEYS_DIR/ssh_host_ed25519_key"
chmod 644 "$SSH_KEYS_DIR/ssh_host_ecdsa_key.pub" "$SSH_KEYS_DIR/ssh_host_ed25519_key.pub"

# Disable default ephemeral host keys from /etc/ssh/sshd_config.
sed -i 's/^HostKey /# HostKey /' /etc/ssh/sshd_config

cat >/etc/ssh/sshd_config.d/custom.conf <<CONF
PasswordAuthentication yes
PubkeyAuthentication no
KbdInteractiveAuthentication no
ChallengeResponseAuthentication no
AuthenticationMethods password
PermitRootLogin no
HostKey $SSH_KEYS_DIR/ssh_host_ecdsa_key
HostKey $SSH_KEYS_DIR/ssh_host_ed25519_key
CONF

/usr/sbin/sshd

exec /usr/local/bin/proxy_manager
