#!/bin/bash

user=$1
pass_file=$2
host=$3
deployment_id=$4
agent_server=$5
agent_id=$6
backend_api=$7
agent_hub_uri=$8
ssh_ports=$9
platform_launcher_abs_path=${10}
rmq_client=${11}
rmq_client_config=${12}

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], trying to find common OS script"
		common_script_path=$(Read_Config "$linux_config_file" "$arch_out:$os_id:common")
		if [ -z "$common_script_path" ]
		then
			message="The OS [$os_id] with [$arch_out] architecture is not supported yet, please contact support team"
			Write_Log "$message" "ERROR"
			timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
			status="Error"
			validation_report="$message"
			Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
			[ -s "$pass_file" ] && rm -f "$pass_file"
			exit 1
		else
			os_script_path="$common_script_path"
		fi
	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 1>&3-) ;} 3>&1
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to create temp folder [$tmp_dir] with output [$out_mkdir]"
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 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 1>&3-) ;} 3>&1
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to upload bootstrap: [$out_upload]"
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 3
	fi

	Write_Log "Update execution attribute for bootstrap"
	{ out_chmod=$( (Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "chmod +x $tmp_dir/bootstrap.sh") 2>&1 1>&3-) ;} 3>&1
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to update attribute for [$tmp_dir/bootstrap.sh] with output [$out_chmod]"
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 4
	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 1>&3-) ;} 3>&1
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Unable to upload password file: [$out_upload_pw]"
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 5
	fi

	Write_Log "Start bootstrap"
	{ out_start=$( (Invoke_SSH_Command "$user" "$pass_file" "$host" "$ssh_enabled_port" "echo `cat $pass_file` | sudo -Sk /bin/bash '$tmp_dir/bootstrap.sh' '$agent_server' '$backend_api' '$agent_hub_uri' '$agent_id' '$deployment_id'") 2>&1 1>&3-) ;} 3>&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 1>&3-) ;} 3>&1
		retcode=$?
		if [ $retcode != 0 ]
		then
			message="Error during cleaning up temporary files: [$out_clean_client]" 
			Write_Log "$message" "ERROR"
			timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
			status="Error"
			validation_report="$message"
		fi
		message="Error during bootstrap start: [$out_start]"	
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message\\\n$validation_report"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 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 1>&3-) ;} 3>&1
	retcode=$?
	if [ $retcode != 0 ]
	then
		message="Error during cleaning up temporary files: [$out_clean_client]" 
		Write_Log "$message" "ERROR"
		timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
		status="Error"
		validation_report="$message"
		Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
		[ -s "$pass_file" ] && rm -f "$pass_file"
		exit 7
	fi

	[ -s "$pass_file" ] && rm -f "$pass_file"
	Write_Log "Bootstrap script completed with success"
else
	message="OS is not detected for host [$host]. OS release: [$os_release_out]. OS architecture: [$arch_out]"
	Write_Log "$message" "ERROR"
	timestamp=$(date -Ins | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	status="Error"
	validation_report="$message"
	Send_Deployment_Message "$rmq_client" "$rmq_client_config" "$agent_id" "$deployment_id" "$timestamp" "$status" "$validation_report"
	[ -s "$pass_file" ] && rm -f "$pass_file"	
	exit 8
fi
