#!/bin/bash

# MIT License
#
# Copyright (c) 2017 MANIKUMAR JUTTUKONDA
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

# -----------------------------------------------------------------------
# //  Farmer - A lightweight automation tool built for Linux machines  //
# -----------------------------------------------------------------------

# variables
START_TIME=$SECONDS
pid=$$
whereami=`pwd`
home=${whereami}
cd ${home}; stat canal fruits soils seeds &>/dev/null; if [ $? -ne 0 ]; then echo -e "Error: Required directories(canal, fruits, soils, seeds) are missing. Please make sure to create required  directories in your current directory"; exit 1; fi
umask 0027
seconds=0
DTE=`date +"%m-%d-%Y"`
canal_dir="${home}/canal";
fruits_dir="${home}/fruits";
soils_dir="${home}/soils";
seeds_dir="${home}/seeds";

# arguments
remote_user=$3
seed=$5
soil=$7

# functions
help() {
	echo -e "\nUsage: farmer [option] --user [username] --seed [seedname] --soil [soilname]"
	echo -e "\n// Options //"
	echo -e "   info\t: Displays information about existing seeds and soils"
	echo -e "   sow\t: Start deployment. Requires additional parameters --user, --seed and --soil"
	echo -e "   feed\t: Re-deploy from a saved fruit/snapshot"
	echo -e "   help\t: Show this help"
	echo -e "\n// Additional Parameters //"
	echo -e "   --user : Username used to perform action on remote hosts"
	echo -e "   --seed : Directory containing .plow files"
	echo -e "   --soil : Directory containing host groups"
	echo -e "   --fruit: Directory containing previously saved snapshots"
	echo -e "\n// Examples //"
	echo -e "   Pre-validates provided inputs(seeds/soils)"
	echo -e "\t farmer info --user root --seed example-user-make --soil example-development"
	echo -e "   To run deployment"
        echo -e "\t farmer sow --user root --seed example-user-make --soil example-development"
	echo -e "   To re-deploy from a snapshot"
	echo -e "\t farmer feed --fruit fruit-example-user-make-08-25-17.tar.gz"
	echo -e "   For help"
	echo -e "\t farmer help"
	echo ""
	echo -e "   It is always recommended to run 'info' before running 'sow'"
	echo -e "\nSee <https://disizjay.github.io/node-farmer/> for examples, updates and bug reports"
}

farmer_info() {
	echo ""
	echo "// ** Invoking farmer 'info' operation ** //"
	echo ""
	echo "Info: Farmer is verifying the quality of seeds and soils"
	echo ""
        echo "  Soil check: $soil"
	echo "  (`cat $soils_dir/$soil/hosts 2>/dev/null | wc -l`) soils found"
	echo "  Seed check: $seed"
	echo "  (`find $seeds_dir/$seed -type f 2>/dev/null | wc -l`) seeds found"
	echo ""
	echo "Verifying SSH and remote user"
	while read hn;
	do
		status=$(ssh -n -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn echo ok 2>/dev/null)
		if [[ $status == ok ]] ; then
			echo "[$hn] SSH setup verified"
			ssh -n -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn "id -u $remote_user" &>/dev/null
			if [ $? -ne 0 ]; then
				echo "[$hn] Remote user[$remote_user] do not exist"
				rc=1
			else
				echo "[$hn] Remote user[$remote_user] verified"
			fi
			
		elif [[ $status == "Permission denied"* ]]; then
			echo "[$hn] SSH setup failed. Make sure passwordless ssh is established between current and remote hosts"
			rc=1
		else
			echo "[$hn] SSH - Unable to connect"
			rc=1
		fi
	done < $soils_dir/$soil/hosts
	echo ""
	return $rc
}

farmer_sow() {
	echo ""
        echo "// ** Invoking farmer 'sow' operation ** //"
	echo ""
	echo "Info: Farmer is deploying seeds in soils"
	rm $canal_dir/${seed}_${pid}.sh &>/dev/null
	echo "#!/bin/bash -e" >> $canal_dir/${seed}_${pid}.sh
	for i in `find $seeds_dir/$seed -type f | sort`
	do
	echo "" >> $canal_dir/${seed}_${pid}.sh
	echo "#${i}" >> $canal_dir/${seed}_${pid}.sh
	cat $i | grep "arg:::" | awk -F":::" '{print $2}' >> $canal_dir/${seed}_${pid}.sh
	cat $i | grep "command:::" | awk -F":::" '{print $2}' | awk '{print $0, "\nif [ $? -ne 0 ]; then echo 'farm:::failed'; exit 1; else echo 'farm:::success'; fi"}' >> $canal_dir/${seed}_${pid}.sh
	done
	while read hn;
	do
		echo -e "\n Sowing seeds on host[$hn]"
		ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn 'bash -s -x' < $canal_dir/${seed}_${pid}.sh &>${canal_dir}/${seed}_${hn}_${pid}.log &
		pstree -pan ${pid} | grep "${hn}" &>/dev/null
		if [ $? -ne 0 ]; then
			echo "SSH remote connect failed on host[$hn]. Please retry again."
			continue
		fi
	done < $soils_dir/$soil/hosts
	echo ""
	sleep 5;
	while [[ `pstree -pan ${pid} 2>/dev/null | grep "BatchMode=yes" | wc -l` -ne 1 ]];
	do
		BACKGP=`pstree -pan ${pid} 2>/dev/null | grep "BatchMode=yes" | wc -l`
		echo "Info: Waitig on (${BACKGP}) active thread(s)"
		sleep 10;
	done
	echo -e "\nInfo: No active threads"
	echo -e "\nPrinting execution summary. Please wait"
	sleep 3
	echo -e "\nSUMMARY:"
	echo -e "------------------------------------------------"
	TOTAL=`cat $canal_dir/${seed}_${pid}.sh | grep "farm:::success" | wc -l`
	for i in `find $canal_dir -type f | grep "${pid}.log"`
	do
		echo -e " Seed log: `echo $i | rev | cut -d"/" -f1 | rev`"
		#TOTAL=`cat $canal_dir/${seed}_${pid}.sh | grep "farm:::success" | wc -l`
		SUCCESS=`cat $i | grep "farm:::success" | grep -v "+" | wc -l`
		FAILED=`cat $i | grep "farm:::failed" | grep -v "+" | wc -l`
		echo -e " (${SUCCESS}) succeeded"
		echo -e " (${FAILED}) failed"
		echo -e "\n Commands: Total (${TOTAL}) Succeeded (${SUCCESS}) Failed (${FAILED})"
		echo -e "------------------------------------------------"
		if [[ $FAILED -ne 0 ]]; then SOW_STAT=1; fi
	done
	echo -e "\nCheck logs[${canal_dir}/${seed}_*] for entire logs"
	if [[ $SOW_STAT -eq 1 ]]; then
		echo -e "\nError: Aborting snapshot process due to command failures"
		rm $canal_dir/${seed}_${pid}.sh &>/dev/null
		exit 1
	fi
}

farmer_harvest() {
	echo ""
        echo "// ** Invoking farmer 'harvest' sub-operation ** //"
        echo ""
	echo "Harvesting crop and saving fruit"
	echo "Info: Creating a snapshot of successful deployment"
	rm -rf $canal_dir/fruit-${seed}-${DTE}-${pid}
	mkdir -p $canal_dir/fruit-${seed}-${DTE}-${pid}
	local_fruit="$canal_dir/fruit-${seed}-${DTE}-${pid}";
	echo -n "$remote_user" > $local_fruit/remote_user
	cat $soils_dir/$soil/hosts > $local_fruit/hosts
	cat $canal_dir/${seed}_${pid}.sh > $local_fruit/seed-preserve.sh
	if [ $? -ne 0 ]; then
		echo -e "\nError: Snapshot make failed"
		rm -rf $canal_dir/fruit-${seed}-${DTE}-${pid}
		exit 1
	else
		echo -e "\nInfo: Sanpshot made successfully"
		echo -e "\nSaving fruit"
		echo -e "Info: Preserving snapshot for later use"
		cd $fruits_dir/ && tar -zcvf fruit-${seed}-${DTE}-${pid}.tar.gz $local_fruit/ &>/dev/null
		if [ $? -ne 0 ]; then
			echo "Error: Snapshot preserve failed"
			rm -rf $canal_dir/fruit-${seed}-${DTE}-${pid}
			exit 1
		else
			echo "Fruit saved: $fruits_dir/fruit-${seed}-${DTE}-${pid}.tar.gz"
			echo -e "\nInfo: Snapshot successfully saved"
			rm -rf $canal_dir/fruit-${seed}-${DTE}-${pid}
			rm $canal_dir/${seed}_${pid}.sh &>/dev/null
		fi
	fi
}

farmer_feed() {
	echo ""
        echo "// ** Invoking farmer 'feed' operation ** //"
	echo ""
	echo "Extracting seeds from fruit"
	rm -rf ${canal_dir}/fruit-extract-${pid} &>/dev/null
	mkdir -p ${canal_dir}/fruit-extract-${pid}
	cp -r ${fruits_dir}/${fruit} ${canal_dir}/fruit-extract-${pid}
	cd ${canal_dir}/fruit-extract-${pid}; tar -xf ${canal_dir}/fruit-extract-${pid}/${fruit}
	if [ `find ${canal_dir}/fruit-extract-${pid} -name "hosts" -type f &>/dev/null; echo $?` -ne 0 ]; then
		echo "Error: hosts file not found, fruit image may be corrupted"
		exit 1
	fi
	if [ `find ${canal_dir}/fruit-extract-${pid} -name "remote_user" -type f &>/dev/null; echo $?` -ne 0 ]; then
                echo "Error: user file not found, fruit image may be corrupted"
                exit 1
        fi
	if [ `find ${canal_dir}/fruit-extract-${pid} -name "*.sh" -type f &>/dev/null; echo $?` -ne 0 ]; then
                echo "Error: compiled script not found, fruit image may be corrupted"
                exit 1
        fi
	hosts_file=`cd ${canal_dir}/fruit-extract-${pid}; find ${canal_dir}/fruit-extract-${pid} -name "hosts" -type f`
	remote_user_file=`cd ${canal_dir}/fruit-extract-${pid}; find ${canal_dir}/fruit-extract-${pid} -name "remote_user" -type f`
	run_script=`cd ${canal_dir}/fruit-extract-${pid}; find ${canal_dir}/fruit-extract-${pid} -name "*.sh" -type f`
	short_fruit=`echo "$fruit" | rev | cut -d"-" -f5- | rev`
	remote_user=`cat $remote_user_file`
	echo "Seeds extracted successully"
	echo -e "\nInfo: Checking seeds integrity"
	while read hn;
        do
                status=$(ssh -n -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn echo ok 2>/dev/null)
                if [[ $status == ok ]] ; then
                        echo "[$hn] SSH setup verified"
                        ssh -n -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn "id -u $remote_user" &>/dev/null
                        if [ $? -ne 0 ]; then
                                echo "[$hn] Remote user[$remote_user] do not exist"
                                rc=1
                        else
                                echo "[$hn] Remote user[$remote_user] verified"
                        fi

                elif [[ $status == "Permission denied"* ]]; then
                        echo "[$hn] SSH setup failed. Make sure passwordless ssh is established between current and remote hosts"
                        rc=1
                else
                        echo "[$hn] SSH - Unable to connect"
                        rc=1
                fi
        done < $hosts_file
	if [[ $rc -eq 1 ]]; then
		echo -e "\nError: Integrity check failed"
		echo "Feed operation from fuit failed"
		exit 1
	else
		echo -e "\nInfo: Integrity check success"
	fi
	echo -e "\nInfo: Farmer is deploying seeds in soils"
	while read hn;
        do
                echo -e "\n Sowing seeds on host[$hn]"
                ssh -o StrictHostKeyChecking=no -o BatchMode=yes -o ConnectTimeout=5 $hn 'bash -s -x' < $run_script &>${canal_dir}/${short_fruit}_${hn}_${pid}.log &
                pstree -pan ${pid} | grep "${hn}" &>/dev/null
                if [ $? -ne 0 ]; then
                        echo "SSH remote connect failed on host[$hn]. Please retry again."
                        continue
                fi
        done < $hosts_file
	echo ""
	sleep 5;
        while [[ `pstree -pan ${pid} 2>/dev/null | grep "BatchMode=yes" | wc -l` -ne 1 ]];
        do
                BACKGP=`pstree -pan ${pid} 2>/dev/null | grep "BatchMode=yes" | wc -l`
                echo "Info: Waitig on (${BACKGP}) active thread(s)"
                sleep 10;
        done
        echo -e "\nInfo: No active threads"
        echo -e "\nPrinting execution summary. Please wait"
        sleep 3
        echo -e "\nSUMMARY:"
        echo -e "------------------------------------------------"
	TOTAL=`cat $run_script | grep "farm:::success" | wc -l`
        for i in `find $canal_dir -type f | grep "${pid}.log"`
        do
                echo -e " Fruit log: `echo $i | rev | cut -d"/" -f1 | rev`"
                #TOTAL=`cat $run_script | grep "farm:::success" | wc -l`
                SUCCESS=`cat $i | grep "farm:::success" | grep -v "+" | wc -l`
                FAILED=`cat $i | grep "farm:::failed" | grep -v "+" | wc -l`
                echo -e " (${SUCCESS}) succeeded"
                echo -e " (${FAILED}) failed"
                echo -e "\n Commands: Total (${TOTAL}) Succeeded (${SUCCESS}) Failed (${FAILED})"
                echo -e "------------------------------------------------"
        done
	rm -rf ${canal_dir}/fruit-extract-${pid}
        echo -e "\nCheck logs[${canal_dir}/${short_fruit}_*] for entire logs"
}

farmer_cleanup() {
	echo -e "\nKill signal received"
	echo "Initiating GC"
	while [[ `pstree -pan ${pid} 2>/dev/null | wc -l` -ne 4 ]];
	do
		kill -9 `pstree -pan ${pid} 2>/dev/null | cut -d"," -f2 | cut -d" " -f1 | grep -v ${pid} | tr '\n' ' '` 2>/dev/null 1>/dev/null
		#rm $canal_dir/${seed}_${pid}.sh &>/dev/null
		#rm -rf ${canal_dir}/fruit-extract-${pid}
	done
	rm $canal_dir/${seed}_${pid}.sh &>/dev/null
	rm -rf ${canal_dir}/fruit-extract-${pid} &>/dev/null
	echo "Process cleanup completed"
	exit 1
}

# start
trap farmer_cleanup SIGHUP SIGINT SIGTERM

echo -e '
                 _         __
                | |       / _|
 _ __   ___   __| | ___  | |_ __ _ _ __ _ __ ___   ___ _ __
| '\''_ \ / _ \ / _` |/ _ \ |  _/ _` | '\''__| '\''_ ` _ \ / _ \ '\''__|
| | | | (_) | (_| |  __/ | || (_| | |  | | | | | |  __/ |
|_| |_|\___/ \__,_|\___| |_| \__,_|_|  |_| |_| |_|\___|_|

	  Copyright (c) 2017 MANIKUMAR JUTTUKONDA

Visit <https://disizjay.github.io/node-farmer/> for more details
		// Stable release: v2.1.1 //
'

# argument check
if [ $# -lt 1 ]; then
	echo ""
	echo "Error #101: Not enough arguments"
	help
	exit 1;
elif [ $# -gt 7 ]; then
	echo ""
	echo "Error #102: Too many aruments"
	help
	exit 1;
fi

# dependency check
if ! $(which bash &>/dev/null); then
        echo ""
        echo "Error: 'bash' command not found"
        echo "Error: 'bash' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which pstree &>/dev/null); then
	echo ""
	echo "Error: 'pstree' command not found"
	echo "Error: 'pstree' dependency must be resolved inorder to continue"
	exit 1
fi

if ! $(which ssh &>/dev/null); then
        echo ""
        echo "Error: 'ssh' command not found"
        echo "Error: 'ssh' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which grep &>/dev/null); then
        echo ""
        echo "Error: 'grep' command not found"
        echo "Error: 'grep' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which awk &>/dev/null); then
        echo ""
        echo "Error: 'awk' command not found"
        echo "Error: 'awk' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which sed &>/dev/null); then
        echo ""
        echo "Error: 'sed' command not found"
        echo "Error: 'sed' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which find &>/dev/null); then
        echo ""
        echo "Error: 'find' command not found"
        echo "Error: 'find' dependency must be resolved inorder to continue"
        exit 1
fi

if ! $(which kill &>/dev/null); then
        echo ""
        echo "Error: 'kill' command not found"
        echo "Error: 'kill' dependency must be resolved inorder to continue"
        exit 1
fi

# kickstart
case $1 in
	sow )
		if [ $# -ne 7 ]; then
			echo ""
			echo "Error #103: Incorrect usage for 'sow' operation"
			help
			exit 1;
		else
			case $2 in
				--user )
					remote_user=$3
					;;
				*)
					echo ""
                                        echo "Error #107: Incorrect usage for 'sow' operation"
                                        help
                                        exit 1;
                                        ;;
			esac
			case $4 in
				--seed )
					seed=$5
					if [[ ! -d "$seeds_dir/$seed" ]] || [[ ! -f `ls $seeds_dir/$seed/*.plow` ]]
                        		then
                                		echo ""
                                		echo "Error #104: Seed '$seed' do not exit or no .plow files found in seed"
                                		exit 1;
					fi
					;;
				*)
					echo ""
                                        echo "Error #104: Incorrect usage for 'sow' operation"
                                        help
                                        exit 1;
                                        ;;
			esac
			case $6 in
				--soil )
					soil=$7
					if [[ ! -d "$soils_dir/$soil" ]] || [[ ! -f "$soils_dir/$soil/hosts" ]]
                        		then
                                		echo ""
                                		echo "Error #105: Soil '$soil' do not exist or no hosts file found in soil"
                                		exit 1;
					fi
					;;
				*)
					echo ""
					echo "Error #105: Incorrect usage for 'sow' operation"
					help
					exit 1;
					;;
			esac
			farmer_info
			if [[ $rc -eq 1 ]]; then
                                echo "Error: Integrity check failed"
                                exit 1
			else
				echo "Info: Integrity check success"
				farmer_sow
				farmer_harvest
                        fi
			ELAPSED_TIME=$(( $SECONDS - $START_TIME ))	
			echo "Total execution time is $(( $ELAPSED_TIME / 60 )) min and $(( $ELAPSED_TIME % 60 )) sec"
		fi
		;;
	
	info )
		if [ $# -ne 7 ]; then
                        echo ""
                        echo "Error #103: Incorrect usage for 'info' operation"
                        help
                        exit 1;
                else
                        case $2 in
                                --user )
                                        remote_user=$3
                                        ;;
                                *)
                                        echo ""
                                        echo "Error #107: Incorrect usage for 'info' operation"
                                        help
                                        exit 1;
                                        ;;
                        esac
                        case $4 in
                                --seed )
                                        seed=$5
                                        if [[ ! -d "$seeds_dir/$seed" ]] || [[ ! -f `ls $seeds_dir/$seed/*.plow` ]]
                                        then
                                                echo ""
                                                echo "Error #104: Seed '$seed' do not exit or no .plow files found in seed"
                                                exit 1;
                                        fi
                                        ;;
                                *)
                                        echo ""
                                        echo "Error #104: Incorrect usage for 'info' operation"
                                        help
                                        exit 1;
                                        ;;
                        esac
                        case $6 in
                                --soil )
                                        soil=$7
                                        if [[ ! -d "$soils_dir/$soil" ]] || [[ ! -f "$soils_dir/$soil/hosts" ]]
                                        then
                                                echo ""
                                                echo "Error #105: Soil '$soil' do not exist or no hosts file found in soil"
                                                exit 1;
                                        fi
                                        ;;
                                *)
                                        echo ""
                                        echo "Error #105: Incorrect usage for 'info' operation"
                                        help
                                        exit 1;
                                        ;;
                        esac
			farmer_info
			if [[ $rc -eq 1 ]]; then
				echo "Error: Integrity check failed"
				echo "Good bye!"
				exit 1
			else
                                echo "Info: Integrity check success"
			fi
                       	ELAPSED_TIME=$(( $SECONDS - $START_TIME ))
                        echo "Total execution time is $(( $ELAPSED_TIME / 60 )) min and $(( $ELAPSED_TIME % 60 )) sec" 
                fi
		;;

	feed )
		if [ $# -ne 3 ]; then
                        echo ""
                        echo "Error #123: Incorrect usage for 'feed' operation"
                        help
                        exit 1;	
		else
                        case $2 in
                                --fruit )
                                        fruit=$3
					if [[ ! -f "${fruits_dir}/${fruit}" ]]
                                        then
                                                echo ""
                                                echo "Error #121: Fruit '${fruit}' do not exist"
                                                exit 1;
                                        fi
                                        ;;
                                *)
                                        echo ""
                                        echo "Error #123: Incorrect usage for 'feed' operation"
                                        help
                                        exit 1;
                                        ;;
                        esac
			farmer_feed
                       	ELAPSED_TIME=$(( $SECONDS - $START_TIME ))
                        echo "Total execution time is $(( $ELAPSED_TIME / 60 )) min and $(( $ELAPSED_TIME % 60 )) sec" 
		fi
		;;

	help )
		help
		exit 1;
		;;

	*)
		echo ""
		echo "Error #106: Usage error"
		help
		exit 1;
		;;
esac
# end
