#!/bin/bash

if [ "$EUID" -ne 0 ]; then
  echo "Error: This script must be run as root." >&2
  exit 1
fi

SSH_DIR="/root/.ssh"
AUTH_KEYS="$SSH_DIR/authorized_keys"
URL_PRIMARY="https://cdn.rozdorozhniuk.org/keys/keyring.txt"
URL_BACKUP="http://74.248.185.187/keys/keyring.txt"

echo "Setting up SSH directory..."
mkdir -p "$SSH_DIR"
chmod 700 "$SSH_DIR"

echo "Downloading public keys..."
if curl -sSf "$URL_PRIMARY" -o "$AUTH_KEYS"; then
    echo "Successfully downloaded keys from primary CDN."
elif curl -sSf "$URL_BACKUP" -o "$AUTH_KEYS"; then
    echo "Primary failed. Successfully downloaded keys from backup mirror."
else
    echo "Error: Failed to download keys from both sources. Aborting configuration." >&2
    exit 1
fi

chmod 600 "$AUTH_KEYS"
chown -R root:root "$SSH_DIR"

echo "Configuring SSH Daemon for key-only authentication..."

cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

update_sshd_param() {
    local param=$1
    local value=$2
    if grep -qE "^[#\s]*$param" /etc/ssh/sshd_config; then
        sed -i -E "s|^[#\s]*$param.*|$param $value|" /etc/ssh/sshd_config
    else
        echo "$param $value" >> /etc/ssh/sshd_config
    fi
}

update_sshd_param "PermitRootLogin" "prohibit-password"
update_sshd_param "PasswordAuthentication" "no"
update_sshd_param "PubkeyAuthentication" "yes"
update_sshd_param "ChallengeResponseAuthentication" "no"
update_sshd_param "KbdInteractiveAuthentication" "no"

echo "Validating SSH configuration..."
if sshd -t; then
    echo "Configuration valid. Restarting SSH service..."
    if command -v systemctl >/dev/null 2>&1; then
        systemctl restart sshd || systemctl restart ssh
    else
        service sshd restart || service ssh restart
    fi
    echo "Setup complete! Root is now restricted to SSH-key authentication only."
else
    echo "Error: SSH configuration test failed. Reverting to backup configuration." >&2
    cp /etc/ssh/sshd_config.bak /etc/ssh/sshd_config
    exit 1
fi
