#!/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)"
TARGET_USER="${TARGET_USER:-${SUDO_USER:-root}}"

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

warn() {
  printf '[WARN] %s\n' "$*" >&2
}

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
}

resolve_home_dir() {
  local user_name="$1"
  local home_dir

  home_dir="$(getent passwd "$user_name" | cut -d: -f6 || true)"
  [ -n "$home_dir" ] || fail "Unable to resolve home directory for user: $user_name"

  printf '%s\n' "$home_dir"
}

ensure_authorized_keys() {
  local user_name="$1"
  local home_dir
  local auth_keys

  home_dir="$(resolve_home_dir "$user_name")"
  auth_keys="${home_dir}/.ssh/authorized_keys"

  if [ ! -s "$auth_keys" ]; then
    fail "No usable public key found at ${auth_keys}. Add your SSH public key before disabling password login."
  fi

  log "Found authorized_keys for ${user_name}: ${auth_keys}"
}

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
}

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

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

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

validate_config() {
  if sshd -t; then
    return
  fi

  warn "sshd -t failed, restoring backup: ${BACKUP_PATH}"
  cp -a "$BACKUP_PATH" "$SSHD_CONFIG"
  fail "Invalid sshd_config detected. Original configuration has been restored."
}

require_root

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

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

log "Enabling SSH public key authentication"
set_or_append_config "PubkeyAuthentication" "yes"
set_or_append_config "AuthorizedKeysFile" ".ssh/authorized_keys"

log "Disabling password and interactive keyboard authentication"
set_or_append_config "PasswordAuthentication" "no"
set_or_append_config "KbdInteractiveAuthentication" "no"
set_or_append_config "ChallengeResponseAuthentication" "no"

log "Keeping PAM enabled for session handling"
set_or_append_config "UsePAM" "yes"

log "Validating sshd configuration"
validate_config

log "Reloading sshd"
reload_or_restart_sshd

printf 'SSH password login has been disabled.\n'
printf 'SSH key login is active for %s.\n' "$TARGET_USER"
printf 'Backup saved to %s\n' "$BACKUP_PATH"
