#!/usr/bin/sh

set -e

# Tango fails if the testbed's FQDN can't be resolved, which seems to happen
# in Incus containers.  Fix this up.
canonical_hostname="$(hostname -f)"
if ! echo "$canonical_hostname" | grep -Fq .; then
	canonical_hostname="$(hostname -A | cut -d' ' -f1)"
	(grep -v '^127\.0\.1\.1[[:space:]]' /etc/hosts; \
	 echo "127.0.1.1 $canonical_hostname $(hostname)") >/etc/hosts.new
	mv /etc/hosts.new /etc/hosts
fi

. /etc/tangorc

HOST=$(echo $TANGO_HOST | sed -e "s/:[[:digit:]]*//")

pstree

# These stops and starts seem to be needed, as a work around.
# The first time tango-starter starts, there is an ENOENT, even if the service
# seems active.
#
# See https://gitlab.com/tango-controls/starter/-/issues/25#note_1499130131

systemctl stop tango-starter
systemctl stop tango-accesscontrol
systemctl stop tango-db

sleep 3

systemctl start tango-db

sleep 5

systemctl start tango-accesscontrol

sleep 5

systemctl restart tango-starter

# Give *enough* time to Starter for being able to be ping'ed
sleep 10

pstree

tango_admin --ping-device dserver/Starter/${HOST}

# test https://bugs.debian.org/1062979:
#
tango_admin --add-property sys/tg_test/1 key value

# check if the property was actually inserted in the related table:
#
mysql -u root -D tango --disable-column-names --silent \
    --execute "SELECT IFNULL( (SELECT device FROM property_device_hist \
      WHERE device = 'sys/tg_test/1' AND name = 'key' AND value = 'value' \
      LIMIT 1) ,'not found');" \
    | grep -v "not found"
