#!/bin/bash
# OS deployment postinstall script, to be run with colibri_runonce service on first start after reboot before logon prompt
if [ $# -eq 0 ]
  then
    #No arguments supplied, PARAMx placeholders should be replaced with values upfront 
	osimageserver=PARAM1
	deployment_id=PARAM2
	computer_id=PARAM3
	rmqserver=PARAM4
	agent_server="PARAM5"
  else
  	osimageserver=$1
	deployment_id=$2
	computer_id=$3
	rmqserver=$4
	agent_server="$5"
fi
is_os_deployment=True
delete_db=False
backend_api="${agent_server/agentapi/api}"
agent_hub_uri="${agent_server/agentapi/signalr}"
log_folder="/var/log/colibri"
log_file_path="$log_folder/postinstall.log"

function Write_Log {
	message=$1
	severity=$2

	if [[ $severity == "" ]]; then severity="INFO"; fi
	#timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	offset=$(date +%z | sed 's/./&:/3')
	timestamp=$(date '+%Y-%m-%dT%H:%M:%S.%7N')$offset
	log_line="[$timestamp][${severity^^}]: $message"
	echo $log_line | tee -a "$log_file_path"
}

function Send_Message {
	message=$1
	status=$2
	vhost="/"
	exchange="os-deployment-result"
	routingkey="os-deployment-result"

	#timestamp=$(date --iso-8601=ns | sed -E 's/(.*),([0-9]{7}).*(\+|-.*)/\1.\2\3/')
	offset=$(date +%z | sed 's/./&:/3')
	timestamp=$(date '+%Y-%m-%dT%H:%M:%S.%7N')$offset
	msg="{
		\"minionid\": $computer_id,
		\"deploymentid\": $deployment_id,
		\"status\": \"$status\",
		\"statusDesc\": \"$message\",
		\"invokedOn\": \"$timestamp\"
		}"
	Write_Log "Sending message: $msg"
	$tmp_dir/rmqclient -h $rmqserver -v $vhost -e $exchange -r $routingkey "$msg"
}

[ -d "$log_folder" ] || mkdir -p "$log_folder"
Write_Log "Postinstall configuration started"

echo  POSTINSTALL CONFIGURATION, PLEASE WAIT...
echo  POSTINSTALL CONFIGURATION, PLEASE WAIT...  > /dev/kmsg
sleep 6

rnd=$(echo $RANDOM | md5sum | head -c 6)
tmp_dir="/tmp/colibri-$rnd"
linux_config_file="$tmp_dir/linux.conf"

mkdir -p $tmp_dir/common
wget -r -nH --cut-dirs=5 --no-parent --reject="index.html*" http://$osimageserver/service_repo/agent/linux/packages/common/ -P $tmp_dir/common
wget http://$osimageserver/service_repo/agent/linux/linux.conf -P $tmp_dir
wget http://$osimageserver/osimages/pefiles/rmqclient -P $tmp_dir
chmod +x $tmp_dir/rmqclient

# Identify Linux type and version
os_id=$(cat /etc/os-release |  sed -n 's/^ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
version_id=$(cat /etc/os-release |  sed -n 's/^VERSION_ID=\(.*\)$/\1/p' | sed -e 's/^"//' -e 's/"$//')
arch_out=$(uname -m)
Write_Log "Detected OS: [$arch_out]:[$os_id]:[$version_id]"
versioned_script_path=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:$os_id:$version_id"='\(.*\)'$/\1/p")
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=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:$os_id:common"='\(.*\)'$/\1/p")
	if [ -z "$common_script_path" ]
	then
		Write_Log "Detect OS using package manager details."
		package_manager=$(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=$(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=$(dpkg -l --no-pager 2>/dev/null | grep -c '^ii')
		rpm_package_count=$(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=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:rpm:platform"='\(.*\)'$/\1/p")
		fi
		if [ "$package_manager" == "apt" ] && [ "$package_type" == "deb" ] && [ $deb_package_count -gt 0 ]; then
			Write_Log "Detected platform Linux_Deb"
			common_script_path=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:deb:platform"='\(.*\)'$/\1/p")
		fi
		if [ "$package_manager" == "apt" ] && [ "$package_type" == "rpm" ] && [ $rpm_package_count -gt 0 ]; then
			Write_Log "Detected platform Linux_Alt"
			common_script_path=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:alt:platform"='\(.*\)'$/\1/p")
		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 3
		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

# Perform preinstallation configuraton
case $os_id in
	redos)
		ssh-keygen -A
		if [ ${os_id:0:1} == "7" ]
		then 
			authselect opt-out
			cp /etc/authselect/user-nsswitch.conf /etc/authselect/user-nsswitch.conf.bak
			sed -i '/^hosts:/s/files.*/files dns /' /etc/authselect/user-nsswitch.conf
			authselect apply-changes
		fi
		cp /etc/nsswitch.conf /etc/nsswitch.conf.bak
		sed -i '/^hosts:/s/files.*/files dns /' /etc/nsswitch.conf
	;;
	altlinux)
		control sudowheel enabled
	;;
	osnova)
		json='{"/opt/colibri/agent/service/Colibri.Agent.Service":{"flags":"m"},"/opt/colibri/agent/ui/Colibri.Agent.DesktopApp":{"flags":"m"}}'
		echo $json  > /etc/paxrat/conf.d/colibri-agent.conf
	;;
esac

bootstrap_script="http://$osimageserver/service_repo/agent/linux/packages/$os_script_path/bootstrap.sh"
Write_Log "Downloading bootstrap $bootstrap_script"
wget $bootstrap_script -P $tmp_dir
chmod +x $tmp_dir/bootstrap.sh

Write_Log "Starting bootstrap with parameters: $delete_db $backend_api $agent_hub_uri $computer_id $deployment_id $is_os_deployment"
$tmp_dir/bootstrap.sh $delete_db $backend_api $agent_hub_uri $computer_id $deployment_id $is_os_deployment
retcode=$?
if [ $retcode != 0 ]
then
	Send_Message "Postinstall: Error $retcode during Colibri agent bootstrap run. Check postinstall tasks status or logs in client folder /var/log/colibri/agent for details." "Error"
	exit 6
fi
#if ls /var/log/colibri/agent/err*.clef 1> /dev/null 2>&1 
#then
#	Send_Message "Postinstall: Error running Colibri agent setup. Check logs in client folder /var/log/colibri/agent for details." "Error"
#	cd /var/log/colibri/agent 
#	for filename in err*.clef; do mv -b "$filename" "_$filename"; done
#	exit 7
#fi

# Perform postinstallation configuraton
case $os_id in
	osnova)
		setfattr -n user.pax.flags -v m /opt/colibri/agent/service/Colibri.Agent.Service
		setfattr -n user.pax.flags -v m /opt/colibri/agent/ui/Colibri.Agent.DesktopAp
	;;
esac

Write_Log "Bootstrap script completed successfully"
Send_Message "Deployment finished." "Success"

Write_Log "Removing temp folder $tmp_dir"
rm -rf $tmp_dir
systemctl disable colibri_runonce
systemctl reboot