#!/bin/bash

# KNEL 2FA Module
# Configures two-factor authentication via Google Authenticator

set -euo pipefail

echo "Running 2FA module..."

# Install Google Authenticator for PAM
DEBIAN_FRONTEND="noninteractive" apt-get -y install \
    libpam-google-authenticator \
    qrencode

# Configure PAM for SSH with 2FA (use nullok for gradual rollout)
if [[ -f ./configs/sshd-pam ]]; then
    cp ./configs/sshd-pam /etc/pam.d/sshd
fi

# Configure SSH to allow challenge-response authentication
if [[ -f ./configs/sshd-2fa-config ]]; then
    # Backup existing config
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
    
    # Add 2FA settings to SSH config
    cat ./configs/sshd-2fa-config >> /etc/ssh/sshd_config
fi

# Restart SSH service
systemctl restart ssh

echo "2FA module completed"
echo "Note: Users must run 'google-authenticator' to set up their 2FA tokens"