#!/bin/bash

echo "-- $0 --"

USE="-X" emerge --newuse openssh

if [ ! -e /etc/ssh/sshd_config.bck ]; then 
  cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bck
fi

cat >/etc/ssh/sshd_config <<_EOF_
HostKey /etc/ssh/ssh_host_ed25519_key
HostKeyAlgorithms ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519-cert-v01@openssh.com,ssh-ed25519,sk-ssh-ed25519@openssh.com

Port 22
Protocol 2

PermitRootLogin without-password
ChallengeResponseAuthentication no
PasswordAuthentication no
# UsePAM no -> not compled in -> warninig
AuthenticationMethods publickey
PubkeyAuthentication yes
PermitEmptyPasswords no

AllowTcpForwarding yes
X11Forwarding no
PrintMotd no
PrintLastLog no
TCPKeepAlive yes

# disable for security reasons
# Subsystem       sftp    /usr/lib/misc/sftp-server

KexAlgorithms curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com

IgnoreRhosts yes
HostbasedAuthentication no

_EOF_

# todo:
# disable password login
# add keys

cat >/etc/motd <<_EOF_
+---------------------------------------------+
| unauthorized use is prohibited              |
| el uso no autorizado está prohibido         |
| несанкционированное использование запрещено |
+---------------------------------------------+
_EOF_

# allow remote login with ssh key
if [ -z ${ROOTKEY+x} ]; then
  echo "variable ROOTKEY is not set"
else
  echo "variable ROOTKEY is set to ${ROOTKEY}"
  [ -d /root/.ssh ] || mkdir -m 600 /root/.ssh
  echo "${ROOTKEY}" >>/root/.ssh/authorized_keys
  chmod 600 /root/.ssh/authorized_keys
fi

# enable and start the service
if [ "${SYSTEMD}" = "0" ] ; then
  rc-config add sshd
  /etc/init.d/sshd start
else
  systemctl enable sshd
  systemctl start sshd
fi
