#!/bin/bash

user=$1
pass_file=$2
host=$3
deployment_id=$4
delete_db=$5
agent_id=$6
backend_api=$7
agent_hub_uri=$8
ssh_ports=$9
platform_launcher_abs_path=${10}

Write_Log "Linux platform script started"
for port in $ssh_ports
do
	Test_Port "$host" "$port"
	ret_port=$?
	if [[ $ret_port == 0 ]]
	then
		ssh_enabled_port=$port
		break
	fi
done

os_release_out=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "cat /etc/os-release")
os_release_ret=$?

arch_out=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "uname -m")
arch_ret=$?

platform_root=$(dirname "$platform_launcher_abs_path")
linux_config_file="$platform_root/linux.conf"

if [[ $((os_release_ret + arch_ret)) == 0 ]]
then
	# Identify Linux type and version
	os_id=$(echo "$os_release_out" |  sed -n 's/^ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
	version_id=$(echo "$os_release_out" |  sed -n 's/^VERSION_ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
	Write_Log "Detected OS: [$arch_out]:[$os_id]:[$version_id]"
	versioned_script_path=$(Read_Config "$linux_config_file" "$arch_out:$os_id:$version_id")
	if [ -z "$versioned_script_path" ]
	then
		Write_Log "There is no special script for the version [$version_id] of OS [$os_id] with [$arch_out]"
		common_script_path=$(Read_Config "$linux_config_file" "$arch_out:$os_id:common")
		if [ -z "$common_script_path" ]
		then
			Write_Log "Detect OS using package manager details."
			package_manager=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "if (command -v apt &>/dev/null || command -v apt-get &>/dev/null) && [ -d /etc/apt ]; then echo apt; elif command -v dnf &>/dev/null && [ -d /etc/dnf ]; then echo dnf; elif command -v yum &>/dev/null && [ -d /etc/yum.repos.d ]; then echo yum; else echo Unsupported; fi")
			package_type=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "if command -v dpkg &>/dev/null; then echo deb; elif command -v rpm &>/dev/null; then echo rpm; else echo Unsupported; fi")
			deb_package_count=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "dpkg -l --no-pager 2>/dev/null | grep -c '^ii'")
			rpm_package_count=$(Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "rpm -qa 2>/dev/null | wc -l")

			Write_Log "Current OS uses Package Manager [$package_manager] and Package type [$package_type]."
			
			if [ $package_manager == "yum" ] || [ $package_manager == "dnf" ]; then
				Write_Log "Detected platform Linux_Rpm"
				common_script_path=$(Read_Config "$linux_config_file" "$arch_out:rpm:platform")
			fi
			if [ $package_manager == "apt" ] && [ $package_type == "deb" ] && [ $deb_package_count -gt 0 ]; then
				Write_Log "Detected platform Linux_Deb"
				common_script_path=$(Read_Config "$linux_config_file" "$arch_out:deb:platform")
			fi
			if [ $package_manager == "apt" ] && [ $package_type == "rpm" ] && [ $rpm_package_count -gt 0 ]; then
				Write_Log "Detected platform Linux_Alt"
				common_script_path=$(Read_Config "$linux_config_file" "$arch_out:alt:platform")
			fi

			if [ -z "$common_script_path" ]; then
				message="Detected OS [$arch_out]:[$os_id]:[$version_id] with Package manager [$package_manager] and Package type [$package_type] is not supported yet, please contact support team"
				Write_Log "$message" "ERROR"
				Send_Message "$message" "Error"
				Exit_Script 1
			fi
		else
			Write_Log "There is a script detected for the of OS [$os_id] with [$arch_out]"
		fi
		os_script_path="$common_script_path"
	else
		os_script_path="$versioned_script_path"
	fi

	# Copy detected script to the target machine and start
	common_files="$platform_root/packages/common/"
	bootstrap_script="$platform_root/packages/$os_script_path/bootstrap.sh"
	
	rnd=$(echo $RANDOM | md5sum | head -c 6)
	tmp_dir="/tmp/colibri-$rnd/"

	Write_Log "Create an empty temp folder for bootstrap"
	out_mkdir=$( (Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "mkdir $tmp_dir") 2>&1)
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to create temp folder [$tmp_dir] with output [$out_mkdir]"
		Write_Log "$message" "ERROR"
		Send_Message "$message" "Error"
		Exit_Script 2
	fi

	Write_Log "Upload bootstrap"
	out_upload=$( (sshpass -f "$pass_file" scp -o "StrictHostKeyChecking=no" -O -P "$ssh_enabled_port" -r "$common_files" "$bootstrap_script" "$user@$host:$tmp_dir") 2>&1)
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to upload bootstrap: [$out_upload]"
		Write_Log "$message" "ERROR"
		Send_Message "$message" "Error"
		Exit_Script 3
	fi

	Write_Log "Upload password file"
	out_upload_pw=$( (sshpass -f "$pass_file" scp -o "StrictHostKeyChecking=no" -O -P "$ssh_enabled_port" -r "$pass_file" "$user@$host:$pass_file") 2>&1)
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to upload password file: [$out_upload_pw]"
		Write_Log "$message" "ERROR"
		Send_Message "$message" "Error"
		Exit_Script 5
	fi

	Write_Log "Start bootstrap"
	out_start=$( ( (cat $pass_file; echo) | Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "sudo -Sk /bin/bash '$tmp_dir/bootstrap.sh' '$delete_db' '$backend_api' '$agent_hub_uri' '$agent_id' '$deployment_id'") 2>&1)
	retcode=$?
	if [ $retcode != 0 ]
	then
		validation_report=""
		out_clean_client=$( (Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "rm -rf $tmp_dir $pass_file") 2>&1)
		retcode=$?
		if [ $retcode != 0 ]
		then
			validation_report="Error during cleaning up temporary files: [$out_clean_client]" 
			Write_Log "$validation_report" "ERROR"
		fi
		message="Error during bootstrap start: [$out_start]"	
		Write_Log "$message" "ERROR"
		validation_report="$message\\\n$validation_report"
		Send_Message "$validation_report" "Error"
		Exit_Script 6
	fi
	
	Write_Log "Cleanup client files"
	out_clean_client=$( (Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "rm -rf $tmp_dir $pass_file") 2>&1)
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Error during cleaning up temporary files: [$out_clean_client]" 
		Write_Log "$message" "ERROR"
		Send_Message "$message" "Error"
		Exit_Script 7
	fi

	Write_Log "Bootstrap script completed with success"
	Exit_Script
else
	message="OS is not detected for host [$host]. OS release: [$os_release_out]. OS architecture: [$arch_out]"
	Write_Log "$message" "ERROR"
	Send_Message "$message" "Error"
	Exit_Script 8
fi