#!/bin/bash
breaksold='v2.4\.'
esgfver=`/usr/local/bin/esg-node --version|grep Version|cut -d ' ' -f2`
mkfifo /tmp/inputpipe
mkfifo /tmp/outputpipe
sleep 7200 >/tmp/inputpipe &
proc=$!
declare -A va
declare -A clearedips
trap ctrl_c INT
function ctrl_c(){
	echo "got a ctrl-c. Cleaning up.";
	kill -9 $proc;
	rm -f /tmp/outputpipe;
	rm -f /tmp/inputpipe;
	rm -f /tmp/answers;
	exit 0;
}
function get_double_entry(){
	local l1
	local l2
	while [ 1 ]; do
		read -e -p "Enter $1: " l1
		alnumpass=`echo $l1|tr -cd '[[:alnum:]]'`
		if [ "$l1" = '' ]; then
			continue;
		fi
		if [ "$l1" != "$alnumpass" ]; then
			continue;
		fi
		read -e -p "Re-enter $1: " l2
		if [ "$l1" != "$l2" ]; then
			continue;
			else break;
		fi
	done
	echo "$l1";
}
function get_entry(){
	local l1
	if [ "$2" != '' ]; then
		read -e -p "Enter $1 ($2): " l1;
		if [ "$l1" = '' ]; then
			echo "$2";
			return;
		fi
	else
	read -e -p "Enter $1: " l1;
	fi
	if [ "$3" != '' -a "$l1" = '' ]; then
		while [ 1 ]; do
			read -e -p "Value for $1 cannot be blank; Enter $1: " l1;
			if [ "$l1" != '' ]; then
				break;
			fi
		done
	fi
	echo "$l1";
}
function register_globus_myproxy(){
	echo -e "Do you wish to register your Myproxy server with Globus (Y/n)? If you select no, gridftp downloads by users will not work.";
	read -e register_globus_choice;
	if [ "$register_globus_choice" != 'n' -a "$register_globus_choice" != 'N' ]; then
		register_globus_choice='Y';
	fi
}
function get_cleared_ips(){

	ct=0
	while [ 1 ]; do
		echo -e "Enter a single ip address which would be cleared to access admin restricted pages.\nYou will be prompted if you want to enter more ip-addresses";
		read -e ip;
		if [ "$ip" = '' ]; then
			continue;
		fi
		clearedips[$ct]=$ip;
		ct=`expr $ct + 1`;
		echo "Do you wish to allow further ips? (y/N)";
		read -e resp
		clearedips[$ct]=$resp;
		if [ "$resp" != 'y' -a "$resp" != 'Y' ]; then
			clearedips[$ct]='n';
			break;
		fi
		ct=`expr $ct + 1`;
	done
}
function load_pipe(){
	if [ $tosave -eq 1 ]; then
		mkdir -p /opt/esgf
		cp /tmp/answers /opt/esgf
	fi
	numprompts=`cat /tmp/answers|wc -l`;
	numpauses=`cat /tmp/answers|grep pause|wc -l`;
	numprompts=`expr $numprompts - $numpauses`;
	if cat /tmp/answers|grep ^'#' >/dev/null; then
		numprompts=`expr $numprompts - 1`;
	fi
	promptct=0
	while read line; do
		if echo $line|grep ^'#' >/dev/null; then
			continue;
		fi
		ans=`echo $line|cut -d ':' -f1`;
		if [ "$ans" = "blank" ]; then
			ans="";
		fi
		if [ "$ans" = "pause" ]; then
			echo "Now waiting for ping-back from installer.";
			cat </tmp/outputpipe
			continue;
		fi
		promptct=`expr $promptct + 1`;
		echo "$ans" >/tmp/inputpipe
		echo "Answered question $promptct of $numprompts";
	done</tmp/answers
	echo "All prompts have now been answered. Do not terminate this script till the installation completes fully.";
	cat </tmp/outputpipe
	kill -9 $proc;
	rm -f /tmp/outputpipe;
	rm -f /tmp/inputpipe;
	rm -f /tmp/answers;
	exit 0;
}
echo "Do you wish to save the answer file from this questionnaire for later use? (n/Y)"
read -e choice;
tosave=1
if [ "$choice" = "n" -o "$choice" = "N" ]; then
	tosave=0;
	else 
	echo "Your choices will be stored in /opt/esgf/answers";
	tosave=1;
fi
echo "Do you wish to load in an answer file from an earlier run? (y/N)"
read -e choice;
if [ "$choice" = "y" -o "$choice" = "Y" ]; then
	while [ 1 ]; do
		echo "Provide path to answer file";
		read -e anspath;
		if [ -s $anspath ]; then
			break;
		fi
		echo "File $anspath does not exist";
	done
	brokenanswers=0
	if cat $anspath|grep ^'#' >/dev/null; then
		oldver=`head -1 $anspath|cut -d '#' -f2`;
		if ! echo $oldver|grep $breaksold >/dev/null; then
			brokenanswers=1;
		fi
	else
		brokenanswers=1;
	fi
	if [ $brokenanswers -eq 0 ]; then
		cp $anspath /tmp/answers;
		chmod 400 /tmp/answers;
		echo "Ready with the answers. You can now run the installer with a </tmp/inputpipe";
		echo "Use CTRL-C at the end of the install, to cleanup.";
		load_pipe
	else
		echo -e "The answers file specified by you was incompatible with this version of the installer and will not be used.\n";
	fi
fi
while [ 1 ]; do
	echo "setup-autoinstall supports type 'all' and type 'data' installs. Which type do you want to install?(all/data)";
	read -e resp;
	if [ "$resp" != "all" -a "$resp" != "data" ]; then
		echo "Invalid type specified";
		continue;
	fi
	install_type=$resp;
	break;
done
ext_idp='n'
if [ "$install_type" = "data" ]; then
	ext_idp='y';
else
	echo "Do you wish to use an external IDP peer?(N/y)";
	read -e resp;
	if [ "$resp" = "y" -o "$resp" = "Y" ]; then
		ext_idp='y';
	fi
fi
if [ "$ext_idp" = "y" ]; then
	while [ 1 ]; do
		echo "Specify your IDP peer's FQDN:";
		read -e idppeer;
		if [ "$idppeer" != '' ]; then
			break
		fi
	done
fi
ip addr show|grep -w inet|grep -v 127.0.0.1|awk '{print $2}'|cut -d '/' -f1 >ips
declare -A ipaddrs
numl=`cat ips|wc -l`;
ct=0
if [ $numl -gt 1 ]; then
	for (( num=1; num<=$numl; num++ )); do
		ip=`cat ips|head -$num|tail -1`;
		ipaddrs[$ct]=$ip;
		ct=`expr $ct + 1`;
	done
	while [ 1 ]; do
		echo "The following ip addresses were found configured on this machine. Specify which is to be used.";
		for n in ${!ipaddrs[@]}; do
			echo  "[$n] ${ipaddrs[$n]}";
		done
		read -e choice;
		invalid=1;
		for n in ${!ipaddrs[@]}; do
			if [ "$n" = "$choice" ]; then
				invalid=0;
				break;
			fi
		done
		if [ $invalid -eq 1 ]; then
			echo "Invalid choice. Try again";
			continue;
		else
			break;
		fi
	rm -f ips
	done

	if [ "$install_type" = "all" ]; then
		if [ "$ext_idp" = "y" ]; then
			vl=("esgfver" 'fix-1' 'ipchoice' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
			'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
			'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-choice' 'ext-idp-val' 'fix-20'
			'fix-21' 'fix-22' 'regglobus' 'globususername' 'globuspassword' 'fix-23' 'fix-24' 'regglobus2' 'fix-25' 'fix-26' 'fix-29')
		else
			vl=("esgfver" 'fix-1' 'ipchoice' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
			'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
			'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-choice' 'fix-21' 'fix-22' 'regglobus' 'globususername'
			'globuspassword' 'fix-23' 'fix-24' 'regglobus2' 'fix-25' 'fix-26')
		fi
	else
		vl=("esgfver" 'fix-1' 'ipchoice' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
		'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
		'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-val' 'fix-20'
		'fix-21' 'fix-22' 'regglobus' 'globususername' 'globuspassword' 'install-compute' 'fix-29')
	fi
	va['ipchoice']=$choice;
else
	if [ "$install_type" = "all" ]; then
		if [ "$ext_idp" = "y" ]; then
			vl=("esgfver" 'fix-1' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
			'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
			'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-choice' 'ext-idp-val' 'fix-20'
			'fix-21' 'fix-22' 'regglobus' 'globususername' 'globuspassword' 'fix-23' 'fix-24' 'regglobus2' 'fix-25' 'fix-26' 'fix-29')
		else
			vl=("esgfver" 'fix-1' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
			'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
			'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-choice' 'fix-21' 'fix-22' 'regglobus' 'globususername'
			'globuspassword' 'fix-23' 'fix-24' 'regglobus2' 'fix-25' 'fix-26' )
		fi
	else
		vl=("esgfver" 'fix-1' 'fqdn' 'adminpass' 'fix-2' 'orgname' 'shortname' 'longname' 'revdomain' 'peergroup' 'defaultpeer'
		'publishendpoint' 'email' 'fix-3' 'fix-4' 'fix-5' 'publisherpassword' 'fix-6' 'fix-7' 'fix-8' 'fix-9' 'fix-10'
		'fix-11' 'fix-12' 'fix-14' 'fix-15' 'get-cleared-ips' 'fix-16' 'fix-17' 'fix-18' 'fix-19' 'ext-idp-val' 'fix-20'
		'fix-21' 'fix-22' 'regglobus' 'globususername' 'globuspassword' 'install-compute' 'fix-29')
	fi
fi

#Here, we work out some defaults
fqdn=`hostname -f`;
domain=`hostname -d`;
IFS=. read -ra line <<< $domain;
let x=${#line[@]}-1;
mys=''
while [ "$x" -ge 0 ]; do
      #echo -n "${line[$x]}.";
      mys=${mys}${line[$x]}.;
      let x--;
done
revdom=`echo $mys|rev|cut -c 2-|rev`;

va['esgfver']="#$esgfver"
va['fix-1']='y' #are you ready to start
va['fqdn']=`get_entry 'fqdn' $fqdn`
va['adminpass']=`get_double_entry 'admin-password (alpha-numeric only)'`
va['fix-2']=${va['adminpass']}
va['orgname']=`get_entry 'orgname' '' 'notblank'`
va['shortname']=`get_entry 'shortname' '' 'notblank'`
va['longname']=`get_entry 'longname' '' 'notblank'`
va['revdomain']=`get_entry 'revdomain' $revdom`
va['peergroup']=`get_entry 'peergroup' esgf-test`
va['defaultpeer']=`get_entry 'defaultpeer' $idppeer`
defpeer=`echo ${va['defaultpeer']}`
va['publishendpoint']=`get_entry "publishendpoint" $defpeer`
va['email']=`get_entry 'admin-email' '' 'notblank'`
va['fix-3']='n' #external db?
va['fix-4']='blank' #postgresurl
va['fix-5']='blank' #postgresuser esgcet?
va['publisherpassword']=`get_entry 'publisher password' '' 'notblank'`
va['fix-6']=${va['adminpass']} #postgres user dbsuper password
va['fix-7']=${va['adminpass']} #postgres user dbsuper password
va['fix-8']='blank' #default port selection for postgres
va['fix-9']='blank' #publisher system or user
va['fix-10']='y' #is everything correct?
va['fix-11']=${va['orgname']} #org id
va['fix-12']='y' #is DN of csr ok?
#va['fix-13']='y'
va['fix-14']=${va['adminpass']} #truststore pass
va['fix-15']=${va['adminpass']} #truststore pass
#now for setup_apache_frontend
#adding the cleared ips with intermediate 'y's and final non-y response.
get_cleared_ips
va['fix-16']='blank' #dnode user
va['fix-17']='blank' #stick with truststore password
va['fix-18']='n' #don't want to create further users
va['fix-19']='blank' #routable ip address of this host
if [ "$ext_idp" = "y" ]; then
	if [ "$install_type" = "all" ]; then
		va['ext-idp-choice']='y'
	fi
	va['ext-idp-val']=$idppeer
	va['fix-20']='blank' #add certs
else
	va['ext-idp-choice']='n'
fi
va['fix-21']='pause' #waiting for globus pingback
#this is where the new globus registeration choice poser occurs
register_globus_myproxy
va['fix-22']='y' #continue with globus installation
va['regglobus']=$register_globus_choice
va['globususername']=`get_entry 'globus-username' '' 'notblank'`
va['globuspassword']=`get_entry 'globus-password' '' 'notblank'`
if [ "$install_type" = "all" ]; then
	va['fix-23']='pause' #waiting for globus pingback
	va['fix-24']='y' #do you want to install globus? hell, yeah!
	#this is where the new globus registeration choice poser occurs
	va['regglobus2']=${va['regglobus']}
	va['fix-25']=${va['globususername']}
	va['fix-26']=${va['globuspassword']}
fi
#va['fix-27']='y' #install cron?
#va['fix-28']='y' #install another cron?
if [ "$ext_idp" = "y" ]; then
	va['fix-29']='blank' #add certs to truststore
fi
if [ "$install_type" = "data" ]; then
	va['install-compute']=`get_entry 'whether you wish to install COMPUTE role(Y/n)' 'y'`
	va['fix-29']='blank'
fi
echo -n >/tmp/answers;
chmod 600 /tmp/answers;
for val in ${vl[@]}; do
	if [ "$val" = "get-cleared-ips" ]; then
		for i in ${clearedips[@]}; do
			echo "$i:cleared-ip-response" >>/tmp/answers;
		done
		continue;
	fi
	ans=${va[$val]}
	echo $ans:$val >>/tmp/answers;
done
chmod 400 /tmp/answers
echo "Ready with the answers. You can now run the installer with a </tmp/inputpipe";
echo "Use CTRL-C at the end of the install, to cleanup.";
load_pipe
