#/bin/bash

# Set port
if [ "x$BASE_PORT" == "x" ]; then
    BASE_PORT=22
fi

# Set password
if [ "x$AUTH_PASS" != "x" ]; then
    echo "[INFO] Setting linux password" # In the Dockerflie remove the -e
    echo -e "metapass\n$AUTH_PASS\n$AUTH_PASS" | passwd
fi

# Prepare conf
mkdir ${HOME}/custom_ssh
ssh-keygen -f ${HOME}/custom_ssh/ssh_host_rsa_key -N '' -t rsa
ssh-keygen -f ${HOME}/custom_ssh/ssh_host_dsa_key -N '' -t dsa

cat << EOF > ${HOME}/custom_ssh/sshd_config
Port $BASE_PORT
HostKey ${HOME}/custom_ssh/ssh_host_rsa_key
HostKey ${HOME}/custom_ssh/ssh_host_dsa_key
AuthorizedKeysFile  .ssh/authorized_keys
ChallengeResponseAuthentication no
UsePAM yes
Subsystem   sftp    /usr/lib/ssh/sftp-server
PidFile ${HOME}/custom_ssh/sshd.pid
X11Forwarding yes
X11DisplayOffset 10
X11UseLocalhost no
EOF

# Run
echo "[INFO] Now running SSH server on port $BASE_PORT and listening."
/usr/sbin/sshd -D -f ${HOME}/custom_ssh/sshd_config
EXIT_CODE=$?
echo "Exit code: $EXIT_CODE"
if [[ "x$EXIT_CODE" != "x0" ]] && [[ "x$EXIT_CODE" != "x130" ]] ; then
    echo "This exit code is an error, exiting." 
    exit $?
fi
echo ""