#!/usr/bin/env bash

set -euo pipefail

SSHD_CONFIG="/etc/ssh/sshd_config"
BACKUP_PATH="/etc/ssh/sshd_config.bak.$(date +%Y%m%d%H%M%S)"

log() {
  printf '[INFO] %s\n' "$*"
}

fail() {
  printf '[ERROR] %s\n' "$*" >&2
  exit 1
}

require_root() {
  if [ "${EUID:-$(id -u)}" -ne 0 ]; then
    fail "Please run this script as root or with sudo."
  fi
}

set_or_append_config() {
  local key="$1"
  local value="$2"

  if grep -Eq "^[#[:space:]]*${key}[[:space:]]+" "$SSHD_CONFIG"; then
    sed -i -E "s|^[#[:space:]]*${key}[[:space:]]+.*|${key} ${value}|" "$SSHD_CONFIG"
  else
    printf '\n%s %s\n' "$key" "$value" >> "$SSHD_CONFIG"
  fi
}

restart_sshd() {
  if command -v systemctl >/dev/null 2>&1; then
    systemctl restart sshd
    return
  fi

  if command -v service >/dev/null 2>&1; then
    service sshd restart
    return
  fi

  fail "Unable to restart sshd automatically. Restart it manually."
}

require_root

[ -f "$SSHD_CONFIG" ] || fail "Cannot find ${SSHD_CONFIG}."

log "Backing up ${SSHD_CONFIG} to ${BACKUP_PATH}"
cp -a "$SSHD_CONFIG" "$BACKUP_PATH"

log "Disabling DNS reverse lookup"
set_or_append_config "UseDNS" "no"

log "Disabling GSSAPI authentication"
set_or_append_config "GSSAPIAuthentication" "no"

log "Forcing IPv4 to avoid slow IPv6 fallback on legacy hosts"
set_or_append_config "AddressFamily" "inet"

log "Validating sshd configuration"
sshd -t || fail "sshd -t failed. Review ${SSHD_CONFIG} and restore ${BACKUP_PATH} if needed."

log "Restarting sshd"
restart_sshd

printf 'SSH optimization completed.\n'
printf 'Backup saved to %s\n' "$BACKUP_PATH"
