#!/usr/bin/env bash
#
# Checking for optional Perl module dependencies
# It can try to install them automatically on demand

modules="Cache::FastMmap Cache::FileCache DNS::ZoneParse IO::Socket::INET6 Math::BigInt::GMP Net::DNS Net::Ping Pod::WSDL SOAP::Transport::HTTP SQL::Translator#0.09000 SQL::Translator::Diff Text::CSV_XS Apache::DBI"
aptget=`which apt-get 2>/dev/null`
yast2=`which yast2 2>/dev/null`
zypper=`which zypper 2>/dev/null`
cpan=`which cpan 2>/dev/null`

checkModules() {
	index=0
	echo "Checking if all optional Perl dependencies are available..."
	for modt in  $modules
	do
		if echo $modt | grep -q '#'; then
			mod=`echo $modt|cut -d '#' -f 1`;
			ver=`echo $modt|cut -d '#' -f 2`;
		else 
			mod=$modt
			ver=''
		fi
		echo -n "$mod"
		if echo $modt | grep -q '#'; then echo -n " v$ver"; fi
		echo -n ': '

		if perl -e "use $mod $ver" 2>/dev/null; 
		then 
			echo "OK"; 
		else 
			echo "NO"; 
			failed[$index]=$mod
			((index++))
		fi
	done
	if [ "$index" -eq "0" ]
	then
		return 0
	else
		return 1
	fi
}

showMissing() {
	echo; echo "The following are missing:"
	modIndex=0
	while [ ${modIndex} -lt ${#failed[@]} ]
	do
		echo "${failed[$modIndex]}"
		modIndex=$((${modIndex}+1))
	done
}

checkModules
if [ "$?" -eq "0" ]; then echo; echo "Everything fine. All Dependencies are installed."; exit 0; fi

showMissing

if ( test -f /etc/debian_version && [ "$aptget" != "" ] && test -x $aptget); then bDebian=1; else bDebian=0; fi
if ( [ "$cpan" != "" ] && test -x $cpan); then bCpan=1; else bCpan=0; fi
if ( [ "$yast2" != "" ] && test -x $yast2); then bYast2=1; else bYast2=0; fi
if ( [ "$zypper" != "" ] && test -x $zypper); then bZypper=1; else bZypper=0; fi

if [ "$bDebian" -eq 0 ] && [ "$bCpan" -eq 0 ]
then
	echo; echo "Don't know how to install these modules. Please do it by hand"
	exit 0;
fi

echo; echo -n "Should I try to install them automatically? [y|N] "
read res
if [ "$res" != "y" ] && [ "$res" != "Y" ]; then exit 0; fi;

if [ "$bCpan" -eq 1 ];
then
	echo; echo -n "Should I use CPAN? Please note that you have to have a C-Compiler like gcc installed. [Y|n] "
	read res
	if [ "$res" != "y" ] && [ "$res" != "Y" ]  && [ "$res" != "" ]; then bCpan=0; fi;
fi

modIndex=0
while [ ${modIndex} -lt ${#failed[@]} ]
do
	echo "${failed[$modIndex]}"
	if [ "$bCpan" -eq 1 ];
	then
		$cpan ${failed[$modIndex]}
	elif [ "$bDebian" -eq 1 ];
	then
		debPack=${failed[$modIndex]}
		$aptget -y install lib${debPack//::/-}-perl
	elif [ "$bYast2" -eq 1 ];
	then
		yastPack=${failed[$modIndex]}
		$yast2 -i perl-${yastPack//::/-}
	else
		echo "Sorry, don't know how to get this module..."
	fi
	modIndex=$((${modIndex}+1))
done

checkModules
if [ "$?" -eq "1" ]; 
then 
	showMissing
	echo; echo "Sorry, could't install all Dependencies. Try it by Hand."
else
	echo; echo "Everything fine. All Dependencies are installed."
fi
exit 0
