#!/bin/bash

# SSH Configuration Modifier Script
# This script enables root login and password authentication in SSH

# Color output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# SSH config file path
SSH_CONFIG="/etc/ssh/sshd_config"
BACKUP_FILE="/etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)"

# Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}This script must be run as root${NC}"
   exit 1
fi

# Backup the original config
echo -e "${YELLOW}Creating backup of SSH config...${NC}"
cp "$SSH_CONFIG" "$BACKUP_FILE"
if [ $? -eq 0 ]; then
    echo -e "${GREEN}Backup created at: $BACKUP_FILE${NC}"
else
    echo -e "${RED}Failed to create backup${NC}"
    exit 1
fi

# Function to modify SSH config option
modify_ssh_option() {
    local option=$1
    local value=$2
    
    if grep -q "^#\?$option" "$SSH_CONFIG"; then
        # Comment out existing line and add new one
        sed -i "s/^#\?$option.*/$option $value/" "$SSH_CONFIG"
        echo -e "${GREEN}Modified: $option $value${NC}"
    else
        # Append if option doesn't exist
        echo "$option $value" >> "$SSH_CONFIG"
        echo -e "${GREEN}Added: $option $value${NC}"
    fi
}

# Apply SSH configuration changes
echo -e "${YELLOW}Modifying SSH configuration...${NC}"
modify_ssh_option "PermitRootLogin" "yes"
modify_ssh_option "PasswordAuthentication" "yes"

# Validate SSH config syntax
echo -e "${YELLOW}Validating SSH configuration syntax...${NC}"
sshd -t
if [ $? -eq 0 ]; then
    echo -e "${GREEN}SSH config syntax is valid${NC}"
else
    echo -e "${RED}SSH config syntax error detected. Restoring backup...${NC}"
    cp "$BACKUP_FILE" "$SSH_CONFIG"
    exit 1
fi

# Restart SSH service
echo -e "${YELLOW}Restarting SSH service...${NC}"
systemctl restart sshd
if [ $? -eq 0 ]; then
    echo -e "${GREEN}SSH service restarted successfully${NC}"
else
    echo -e "${RED}Failed to restart SSH service. Restoring backup...${NC}"
    cp "$BACKUP_FILE" "$SSH_CONFIG"
    systemctl restart sshd
    exit 1
fi

# Display current settings
echo -e "${YELLOW}Current SSH settings:${NC}"
echo -e "${GREEN}PermitRootLogin: $(grep '^PermitRootLogin' $SSH_CONFIG | awk '{print $2}')${NC}"
echo -e "${GREEN}PasswordAuthentication: $(grep '^PasswordAuthentication' $SSH_CONFIG | awk '{print $2}')${NC}"

echo -e "${GREEN}SSH configuration updated successfully!${NC}"
echo -e "${YELLOW}WARNING: Enabling root login and password authentication may reduce security.${NC}"
echo -e "${YELLOW}Consider using key-based authentication instead.${NC}"