#!/bin/sh
# Copyrighted Georgi Georgiev (C) 2019
# add_cifs_mounts_ips_to_hosts.sh
# Script purpose is to check and keep the IPs of CIFS hostnames present in /etc/fstab to /etc/hosts file
# variable to get IP from nslookup
# resolvedIP=$(nslookup "$1" | awk -F':' '/^Address: / { matched = 1 } matched { print $2}' | xargs)
NOW=$(date +"%Y-%m-%d-%T");
chk_cifs_mounts () {
	if [ "$(grep -i ' cifs ' /etc/fstab |wc -l)" -gt 0 ]; then
		export has_cifs='1';
	else 
		echo 'No cifs fs defined in /etc/fstab .. nothing to do exiting';
	exit 0;
	fi

}

add_curr_ns_records_to_hosts () {
	if [ $has_cifs = '1' ]; then

		for i in $(grep -i ' cifs ' /etc/fstab|awk '{ print $1 }'|grep -v '#' | sed -e 's#/# #g'|awk '{ print $1 }'|sort -rn |uniq); do
			echo "|$i|"
				if [ -n "$i" ]; then

					host=$i
##host_o=$(host "$i"); host=$(echo $host_o | grep 'has address' | awk '{ print $1 }'); ip=$(echo $host_o | grep 'has address' |awk '{ print $4 }');
##echo "|$host_o|"
						ip=$(nslookup "$host" | awk -F':' '/^Address: / { matched = 1 } matched { print $2}' | xargs)
##echo "$ip $host ";
##echo "| $host $ip |"
						if [[ $(grep "$ip $host" /etc/hosts) ]]; then
							echo "Existing $ip $host skipping to add to /etc/hosts";
						else
							echo "Not existing $ip $host Adding to /etc/hosts";
	echo "Taking copy to /root/ of current /etc/hosts in case of future troubles";
	cp -rpf /etc/hosts /root/hosts.$NOW;
##echo "$ip $host"
	echo "# Below record added on $NOW for performance improvement of CIFS / NFS ! DO NOT MANUALLY EDIT ! it will auto refresh" >> /etc/hosts;
	echo "$ip $host" >> /etc/hosts
		fi

		fi
		done

		fi

}

main () {
	chk_cifs_mounts;
	add_curr_ns_records_to_hosts;
}
main;

