#!/bin/bash

read -p "Enter the new username: " username
read -s -p "Enter the password for the new user: " password

# Creating new user
echo "Creating new user $username"
useradd -m -s /bin/bash $username
echo "$username:$password" | chpasswd

# Adding user to sudo group
echo "Adding $username to sudo group"
usermod -aG sudo $username

# Installing Google Authenticator
apt update && apt install libpam-google-authenticator -y

# Setting up Google Authenticator for the new user
su - $username -c "google-authenticator -t -d -f -r 3 -R 30 -w 3"

# Updating SSH configuration to use Google Authenticator
echo "auth required pam_google_authenticator.so" >> /etc/pam.d/sshd

# Updating the rest of the script
echo "Updating package lists and upgrading installed packages"
apt update && apt upgrade -y

echo "Installing UFW, Fail2Ban, and Unattended Upgrades"
DEBIAN_FRONTEND=noninteractive apt install ufw fail2ban unattended-upgrades -y

echo "Setting UFW to deny incoming and allow outgoing connections by default"
ufw default deny incoming
ufw default allow outgoing

echo "Allowing SSH (port 22) in UFW"
ufw allow 22/tcp

echo "Enabling UFW (forcing to bypass prompts)"
ufw --force enable

echo "Disabling root login via SSH"
sed -i 's/^PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config

echo "Changing SSH port to 2222"
sed -i 's/^#Port 22/Port 2222/' /etc/ssh/sshd_config

echo "Restarting SSH service"
systemctl restart sshd

echo "Enabling Fail2Ban service"
systemctl enable fail2ban

echo "Enabling automatic reboot for unattended upgrades"
echo "Unattended-Upgrade::Automatic-Reboot \"true\";" >> /etc/apt/apt.conf.d/50unattended-upgrades

echo "Removing unnecessary packages"
apt autoremove -y

echo "Securing SSH config permissions"
chmod 600 /etc/ssh/sshd_config
chown root:root /etc/ssh/sshd_config

echo "Allowing new SSH port 2222 in UFW"
ufw allow 2222/tcp

echo "Removing the old SSH port 22 rule from UFW"
ufw delete allow 22/tcp

echo "Reloading UFW configuration"
systemctl reload ufw

echo "Disabling IP forwarding and IPv6"
echo "net.ipv4.ip_forward = 0" >> /etc/sysctl.conf
echo "net.ipv6.conf.all.disable_ipv6 = true" >> /etc/sysctl.conf
sysctl -p

echo "Installing AppArmor and setting it to enforce mode"
DEBIAN_FRONTEND=noninteractive apt install apparmor apparmor-utils -y
aa-enforce /etc/apparmor.d/*

echo "Enabling and starting AppArmor"
systemctl enable apparmor
systemctl start apparmor
