#!/bin/bash
cat << EOF 
This script will copy a set of files to /tmp on a set of specified machines. 
This script will copy an additional file with commands to be 
run on the remote machines.

EOF


function write_command() {
	filename=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
	echo "Enter i and paste the command into this file, enter \"<ESC>ZZ\" when you are done "
	echo "Press enter to continue"
	read
	vi /tmp/$filename
	(echo -e "#!/bin/bash\n" && cat /tmp/$filename ) > /tmp/temp_command
	cat /tmp/temp_command > /tmp/$filename
	chmod +x /tmp/$filename
}


function get_host_list() {
	host_filename=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
	echo "Enter i and paste a list of hosts into this file, enter \"<ESC> ZZ\" when you are done "
	echo "Press enter to continue."
	read
	vi /tmp/$host_filename
	echo "What user do you use to connect to these machines?"
	read user 
}

function get_list_of_files {
	file_list=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 10 | head -n 1)
	echo "Enter i and paste a list of files to copy, enter \"<ESC> ZZ\" when you are done "
	echo "Press enter to continue."
	read
	vi /tmp/$file_list
}

function tar_over {
	j=$(cat /tmp/$file_list | tr '\012' ' ')
	for i in `cat /tmp/$host_filename`
	do
		tar cvpf - ${j} | ssh -l $user ${i} "tar xvpf - -C /tmp"
	done
}

function run_command_on_hosts {
	for i in `cat /tmp/$host_filename`
	do
		ssh -l $user ${i} "nohup /tmp/tmp/$filename"
	done
}

function verify_responses {
	echo "These files: "
	cat /tmp/$file_list
	echo -e "\nto these hosts:"
	cat /tmp/$host_filename

	echo -e "\nThese commands will be run on the above hosts"
	cat /tmp/$filename

	echo -e "\nAre you sure? (y/N)"
	read  answer

	if [ "$answer" == "y" ] || [ "$answer" == "Y" ]
	then 
		run_command_on_hosts
	fi
}

function main {
	get_host_list
	write_command
	get_list_of_files
	echo "/tmp/$filename" >> /tmp/$file_list
	tar_over
	verify_responses
}

main
