#!/bin/bash

# ============================================================
# Final SSH Root Login Fix - AlmaLinux 9 / RHEL 9
# ============================================================

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

if [[ $EUID -ne 0 ]]; then
   echo -e "${RED}Run this as root${NC}"
   exit 1
fi

SSH_CONFIG="/etc/ssh/sshd_config"
BACKUP="/etc/ssh/sshd_config.backup.$(date +%Y%m%d_%H%M%S)"

echo -e "${BLUE}=== Final SSH Root Login Fix ===${NC}\n"

# 1. Backup
cp "$SSH_CONFIG" "$BACKUP"
echo -e "${GREEN}Backup saved: $BACKUP${NC}"

# 2. Remove conflicting directives from MAIN config and ALL drop-in files
echo -e "${YELLOW}Cleaning conflicting directives everywhere...${NC}"
for f in "$SSH_CONFIG" /etc/ssh/sshd_config.d/*.conf; do
    [ -e "$f" ] || continue
    sed -i '/^PermitRootLogin/d; /^#PermitRootLogin/d' "$f"
    sed -i '/^PasswordAuthentication/d; /^#PasswordAuthentication/d' "$f"
    sed -i '/^KbdInteractiveAuthentication/d; /^#KbdInteractiveAuthentication/d' "$f"
    sed -i '/^ChallengeResponseAuthentication/d; /^#ChallengeResponseAuthentication/d' "$f"
done
echo -e "${GREEN}Cleaned${NC}"

# 3. Add final override drop-in (loads LAST, wins over everything)
mkdir -p /etc/ssh/sshd_config.d
cat > /etc/ssh/sshd_config.d/zz-root-login.conf << 'EOF'
PermitRootLogin yes
PasswordAuthentication yes
KbdInteractiveAuthentication yes
EOF
echo -e "${GREEN}Created /etc/ssh/sshd_config.d/zz-root-login.conf${NC}"

# 4. Fix SELinux context
if command -v restorecon &>/dev/null; then
    restorecon -Rv /etc/ssh/ &>/dev/null
    echo -e "${GREEN}SELinux context restored on /etc/ssh/${NC}"
fi

# 5. Unlock root / set password if needed
ROOT_STATUS=$(passwd -S root 2>/dev/null | awk '{print $2}')
if [[ "$ROOT_STATUS" == "L" || "$ROOT_STATUS" == "LK" ]]; then
    echo -e "${YELLOW}Root is locked. Unlocking...${NC}"
    passwd -u root
fi
if [[ "$ROOT_STATUS" == "NP" ]]; then
    echo -e "${RED}Root has no password set. Set one now:${NC}"
    passwd root
fi
echo -e "${GREEN}Root account status: OK${NC}"

# 6. Ensure firewalld allows SSH
if systemctl is-active --quiet firewalld; then
    firewall-cmd --permanent --add-service=ssh &>/dev/null
    firewall-cmd --reload &>/dev/null
    echo -e "${GREEN}firewalld: SSH allowed${NC}"
fi

# 7. Validate config syntax
echo -e "${YELLOW}Validating config...${NC}"
sshd -t
if [ $? -ne 0 ]; then
    echo -e "${RED}Syntax error! Restoring backup...${NC}"
    cp "$BACKUP" "$SSH_CONFIG"
    exit 1
fi
echo -e "${GREEN}Config valid${NC}"

# 8. Restart sshd
systemctl restart sshd
echo -e "${GREEN}sshd restarted${NC}"

# 9. Confirm EFFECTIVE running config (ground truth)
echo -e "\n${BLUE}=== Effective SSHD Config (what's actually active) ===${NC}"
sshd -T | grep -Ei "^permitrootlogin|^passwordauthentication|^kbdinteractiveauthentication"

echo -e "\n${BLUE}=== Done ===${NC}"
echo -e "${YELLOW}Test from your local machine with:${NC}"
echo -e "${GREEN}ssh -o PubkeyAuthentication=no root@your_server_ip${NC}"