#!/bin/bash

# KNEL SSH Hardening Module
# Applies SSH security hardening configurations

set -euo pipefail

echo "Running SSH hardening module..."

# Create SSH directories
mkdir -p $ROOT_SSH_DIR

# Setup root SSH keys
if [[ -f ./configs/root-ssh-authorized-keys ]]; then
    cp ./configs/root-ssh-authorized-keys $ROOT_SSH_DIR/authorized_keys
    chmod 400 $ROOT_SSH_DIR/authorized_keys
    chown root: $ROOT_SSH_DIR/authorized_keys
fi

# Setup localuser SSH keys
if [[ $LOCALUSER_CHECK -gt 0 ]]; then
    mkdir -p $LOCALUSER_SSH_DIR
    
    if [[ -f ./configs/localuser-ssh-authorized-keys ]]; then
        cp ./configs/localuser-ssh-authorized-keys $LOCALUSER_SSH_DIR/authorized_keys
        chmod 400 $LOCALUSER_SSH_DIR/authorized_keys
        chown localuser $LOCALUSER_SSH_DIR/authorized_keys
    fi
fi

# Setup subodev SSH keys
if [[ $SUBODEV_CHECK -gt 0 ]]; then
    mkdir -p $SUBODEV_SSH_DIR
    
    if [[ -f ./configs/localuser-ssh-authorized-keys ]]; then
        cp ./configs/localuser-ssh-authorized-keys $SUBODEV_SSH_DIR/authorized_keys
        chmod 400 $SUBODEV_SSH_DIR/authorized_keys
        chown subodev: $SUBODEV_SSH_DIR/authorized_keys
    fi
fi

# Deploy SSH configuration based on environment
if [[ $DEV_WORKSTATION_CHECK -eq 0 ]]; then
    # Production SSH configuration
    if [[ -f ./configs/tsys-sshd-config ]]; then
        cp ./configs/tsys-sshd-config /etc/ssh/sshd_config
    fi
else
    # Development workstation - more permissive settings
    if [[ -f ./configs/tsys-sshd-config ]]; then
        cp ./configs/tsys-sshd-config /etc/ssh/sshd_config
    fi
fi

# Additional SSH hardening for non-Ubuntu systems
if [[ $UBUNTU_CHECK -ne 1 ]] && [[ -f ./configs/ssh-audit-hardening.conf ]]; then
    mkdir -p /etc/ssh/sshd_config.d
    cp ./configs/ssh-audit-hardening.conf /etc/ssh/sshd_config.d/ssh-audit_hardening.conf
    chmod og-rwx /etc/ssh/sshd_config.d/*
fi

# Secure SSH configuration permissions
chmod og-rwx /etc/ssh/sshd_config

echo "SSH hardening module completed"