#!/usr/bin/env bash

. /usr/share/dosis2/bin/shell-support-functions

enforce_root

upg_val=$1
sql_val=${upg_val^^}

if [ -z "$sql_val" ]; then
	sql_val="FALSE"
fi

if [ "$sql_val" != "TRUE" ] && [ "$sql_val" != "FALSE" ]; then
	sql_val="FALSE"
fi

if [ -f "/opt/dosis2/etc/custom/dosisConfig.xml" ]; then
    dafe_tag="`/opt/dosis2/bin/xml-select read /opt/dosis2/etc/custom/dosisConfig.xml \
        --select 'config > section[name=\"general\"] > property[name=\"DafeTag\"] > value' --text`";
 	db_ip="`/opt/dosis2/bin/xml-select read /opt/dosis2/etc/custom/dosisConfig.xml \
 	    --select 'config > section[name=\"general\"] > property[name=\"DBServer\"] > value' --text`";
else
    dafe_tag="UNKNOWN"
    db_ip="127.0.0.1"
fi

dafe_type="`/usr/share/dosis2/bin/dafe-type`"

if [ "$dafe_type" != "SITE_SERVER" ]; then
	if [ "$sql_val" == "TRUE" ]; then
		if [ "$db_ip" == "127.0.0.1" ]; then
			psql -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'LAST_PKG_UPD',timeofday()::text)"
		else
			psql -h $db_ip -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'LAST_PKG_UPD',timeofday()::text)"
		fi
	fi
else
	if [ "$db_ip" == "127.0.0.1" ]; then
		psql -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'IS_SYS_UPGRADE','$sql_val')"
		if [ "$sql_val" == "TRUE" ]; then
			psql -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'LAST_PKG_UPD',timeofday()::text)"
		fi
	else
		psql -h $db_ip -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'IS_SYS_UPGRADE','$sql_val')"
		if [ "$sql_val" == "TRUE" ]; then
			psql -h $db_ip -d dosis2 -U dpg -c "SELECT equipment.update_dafe_status((select id from equipment.dafe where tag = '$dafe_tag'),'LAST_PKG_UPD',timeofday()::text)"
		fi
	fi
fi