#!/usr/bin/env bash

CONFIG_FILE="/etc/ssh/sshd_config"
BACKUP_FILE="/etc/ssh/sshd_config.bak"

# Nur root darf Änderungen machen
if [ "$EUID" -ne 0 ] && [ "$1" != "-s" ]; then
  echo "Bitte mit sudo ausführen."
  exit 1
fi

# Funktion: Aktuellen Status anzeigen
show_status() {
  grep -E "^PasswordAuthentication" "$CONFIG_FILE" | awk '{ print $2 }'
}

# Funktion: Setzen von PasswordAuthentication
set_password_auth() {
  VALUE=$1
  echo "Setze PasswordAuthentication auf '$VALUE' ..."

  # Backup
  cp "$CONFIG_FILE" "$BACKUP_FILE"

  # Setzen oder hinzufügen
  if grep -q "^PasswordAuthentication" "$CONFIG_FILE"; then
    sed -i "s/^PasswordAuthentication.*/PasswordAuthentication $VALUE/" "$CONFIG_FILE"
  else
    echo "PasswordAuthentication $VALUE" >> "$CONFIG_FILE"
  fi

  # SSH-Dienst neustarten
  if systemctl is-active --quiet ssh; then
    systemctl restart ssh
  elif systemctl is-active --quiet sshd; then
    systemctl restart sshd
  else
    echo "SSH-Dienst konnte nicht gefunden werden."
    exit 1
  fi

  echo "Done. PasswordAuthentication ist jetzt '$VALUE'."
}

# Parameter auswerten
case "$1" in
  -y)
    set_password_auth "yes"
    ;;
  -n)
    set_password_auth "no"
    ;;
  -s)
    STATUS=$(show_status)
    echo "Aktueller Status von PasswordAuthentication: ${STATUS:-(nicht gesetzt)}"
    ;;
  *)
    echo "Benutzung:"
    echo "  sudo ./password -y    # aktiviert PasswordAuthentication"
    echo "  sudo ./password -n    # deaktiviert PasswordAuthentication"
    echo "  ./password -s         # zeigt aktuellen Status (kein sudo nötig)"
    exit 1
    ;;
esac