#!/bin/bash
# script was originally written by Vimalraj_Sekar (Intigua)
# Summary: Script handles Disable IPv6 for:
# 1. RedHat 7.x OS / Oracle 7.x OS
# 2. RedHat 8.x OS / AlmaLinux 8.x OS/ Oracle 8.x OS
# 3. RedHat 9.x OS / AlmaLinux 9.x OS/ Oracle 9.x OS
# Format to run the script:
# sh Disable_ipv6.sh 


# This Script check the OS_type and Version to run the script to disable ipv6 if version more than 8.x
# if need to disable ipv6, network interface must be without space, 
#the Network interface also checked for space and change it to network device name if required.


OS_TYPE=$(grep -i ^ID= /etc/os-release | head -n 1 | awk -F= '{print $2}' | tr -d '"')
Version=$(grep -i "VERSION_ID" /etc/os-release | awk -F= '{print $2}' | tr -d '"' | awk -F. '{print $1}')


if [ "$Version" -ge "8" ]; then

# Changing Network Interface name if its having spaces in their name
Interface=$(nmcli device | awk  'NR==2 {print $1}')
 # Checking if Network Interface found or not
    if [ -z "$Interface" ]; then
        echo "No network interface found... exiting ... from ... script"
        exit 1
    fi

InterfaceName=$(nmcli -t -f NAME,DEVICE connection show --active | head -n 1 |awk -F: '{print $1}')
    if echo "$InterfaceName" | grep -q " "; then
        nmcli connection modify "$InterfaceName" connection.id "$Interface"
        NewInterfaceName=$(nmcli dev show "$Interface" | grep "GENERAL.CONNECTION:"| awk -F"GENERAL.CONNECTION:" '{sub(/^ */, "", $2); print $2}')
        echo "Changing the Interface name $InterfaceName to $NewInterfaceName"
    else 
        echo " Interface name doesn't have space , hence skipping .... "
    fi


#Running further to disable IPv6
#nmcli connection modify $Interface ipv6.addresses "" ipv6.gateway ""
#nmcli connection modify $Interface ipv6.method "disabled"
nmcli connection modify $Interface ipv6.addresses "" ipv6.gateway "" ipv6.method "disabled"
# Copy the hosts files
cp -p /etc/hosts /etc/hosts.backup
echo " /etc/hosts file backup has been taken"
sed -i 's/^[[:space:]]*::/#::/' /etc/hosts
touch /etc/sysctl.d/ipv6.conf
cat <<EOL > "ipv6.conf"
# Disable IPv6 for all interfaces
net.ipv6.conf.all.disable_ipv6 = 1

# Disable IPv6 for the loopback interface
net.ipv6.conf.lo.disable_ipv6 = 1

# Disable IPv6 for each network interface
net.ipv6.conf."$Interface".disable_ipv6 = 1

EOL

# Taking backup & Rebuilding the initramfs
cp -p /boot/initramfs-$(uname -r).img /boot/initramfs-$(uname -r).backup.img
dracut -f -v
lsinitrd /boot/initramfs-$(uname -r).img | grep 'ipv6'

sed -i "/^GRUB_CMDLINE_LINUX=/s/\"$/ ipv6.disable=1\"/" "/etc/default/grub"

grubby --update-kernel=ALL --args="ipv6.disable=1"

echo "System is going to reboot...."

echo "..."
reboot
echo"...rebooting..."


else 
nmcli connection modify $Interface ipv6.addresses "" ipv6.gateway ""
nmcli connection modify $Interface ipv6.method "ignore"
   echo " EL7 not required to disable IPv6"
  
fi