#!/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
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 "The version [$version_id] of OS [$os_id] with [$arch_out] architecture is not supported yet, trying to find common OS script"
	common_script_path=$(cat "$linux_config_file" | sed -n "s/^"$arch_out:$os_id:common"='\(.*\)'$/\1/p")
	if [ -z "$common_script_path" ]
	then
		Send_Message "Postinstall: The OS [$os_id] with [$arch_out] architecture is not supported yet, please contact support team" "Error"
		exit 3
	else
		os_script_path="$common_script_path"
	fi
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: $agent_server $backend_api $agent_hub_uri $computer_id $deployment_id $is_os_deployment"
$tmp_dir/bootstrap.sh $agent_server $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