#!/bin/bash
# Created by Steve Hajek - Liquidware Labs - 7/25/2018
# Updated by Ryan Wilp 02/26/2025 - changed service commands to systemctl, updated lwl-backend-priv service name, added lwl-cidd service, removed system_id file steps

# Make sure this gets run as root or with sudo
if [ $(id -u) != "0" ]; then
 echo "Error: You must be root user or use sudo to run this script."
 exit 10
fi
# Get DB server and port for query
PGHOST=`/opt/tnt/bin/tntdbconf PGHOST`
PGPORT=`/opt/tnt/bin/tntdbconf PGPORT`
# Get the HUB's SID from the DB
SID=`echo "select sid from tnt_config.node where id = (select id from tnt_config.policynode where type = 3 and system_object = true);" | PGPASSWORD=reports psql -h $PGHOST -p $PGPORT -t portal reports | awk -F\  '{ print $1 }'`
# Do work...
echo ""
echo "This script will cleanup the HUB's registration files and force it to re-register itself again."
echo "Getting started..."
# Stop the CID service, clean up activation.crt and CID files to force registration call later
systemctl stop vs-helper lwl-cidd
echo "Cleaning up files, pulling cert from DB and installing it..."
echo ""
rm -f /opt/tnt/var/backend/activation.crt /opt/vdesktools/grd/*.txt* /opt/vdesktools/grd/uidcache /opt/vdesktools/grd/key_material/certreq.tnt
# Pull activation.crt fresh from the DB
/opt/tnt/bin/brandall >/dev/null
sleep 1
# Replace the 'bad' mgrcert.pem with the SID and new/correct cert we just pulled from the DB
/opt/tnt/bin/showactcert true $SID >/opt/vdesktools/grd/key_material/public/mgrcert.pem
# Need to stop -priv since we'll be messing with system_id now that CID is ready to go
systemctl stop lwl-backend-priv
sleep 1
echo "NEW HUB SID: `echo $SID`"
# Now we're ready to start the CID and it should register with the HUB again and create a cert.txt
echo ""
echo "Work done, now restarting services..."
systemctl start vs-helper lwl-cidd
echo "Waiting 5 seconds for cert.txt..."
echo ""
sleep 5
# Check if cert.txt exists
if [ -f /opt/vdesktools/grd/cert.txt ]; then
 echo "Success! HUB Event Log should show HUB as registered now."
else
 echo "Doesn't look like it worked, still missing cert.txt."
 echo "Waitig 5 more seconds and checking agian..."
 sleep 5
 ls -l /opt/vdesktools/grd/cert.txt
 echo "Look above, if cert.txt still doesn't exist, something is wrong..."
fi
# Don't forget to start back up -priv
systemctl start lwl-backend-priv
echo ""
echo "Complete."
echo ""
