#!/bin/bash

# Check if running as root
if [ "$(id -u)" != "0" ]; then
    echo "This script must be run as root. Please use sudo or switch to the root user."
    exit 1
fi

# Update package list
echo "Updating package list..."
apt-get update

# Install sudo if not already installed
echo "Checking and installing sudo..."
if ! command -v sudo &> /dev/null; then
    apt-get install -y sudo
    echo "sudo has been installed."
else
    echo "sudo is already installed."
fi

# Add current user to sudo group (if not root)
if [ -n "$SUDO_USER" ]; then
    echo "Adding user $SUDO_USER to sudo group..."
    usermod -aG sudo "$SUDO_USER"
    echo "User $SUDO_USER has been added to the sudo group."
else
    echo "No SUDO_USER detected. Please manually add users to the sudo group if needed."
fi

# Install openssh-server if not already installed
echo "Checking and installing openssh-server..."
if ! dpkg -l | grep -q openssh-server; then
    apt-get install -y openssh-server
    echo "openssh-server has been installed."
else
    echo "openssh-server is already installed."
fi

# Backup SSH configuration file
SSHD_CONFIG="/etc/ssh/sshd_config"
if [ -f "$SSHD_CONFIG" ]; then
    echo "Backing up SSH configuration file..."
    cp "$SSHD_CONFIG" "$SSHD_CONFIG.bak"
fi

# Enable SSH root login
echo "Configuring SSH to allow root login..."
if grep -q "^PermitRootLogin" "$SSHD_CONFIG"; then
    sed -i 's/^PermitRootLogin.*/PermitRootLogin yes/' "$SSHD_CONFIG"
else
    echo "PermitRootLogin yes" >> "$SSHD_CONFIG"
fi

# Ensure password authentication is enabled
if grep -q "^PasswordAuthentication" "$SSHD_CONFIG"; then
    sed -i 's/^PasswordAuthentication.*/PasswordAuthentication yes/' "$SSHD_CONFIG"
else
    echo "PasswordAuthentication yes" >> "$SSHD_CONFIG"
fi

# Restart SSH service
echo "Restarting SSH service..."
systemctl restart sshd

# Check SSH service status
if systemctl is-active --quiet sshd; then
    echo "SSH service has been successfully restarted."
else
    echo "Failed to restart SSH service. Please check the configuration."
    exit 1
fi

echo "Configuration completed!"
echo "1. sudo is enabled, and $SUDO_USER (if applicable) has been added to the sudo group."
echo "2. openssh-server is installed and running."
echo "3. SSH root login is enabled with password authentication."
echo "Please ensure the root account has a strong password for security."