#!/bin/bash

readonly AEMBIT_USER_NAME="aembit"

if [ "$(id --user)" -ne 0 ]; then
    echo "Uninstaller must be run as root."
    exit 1
fi

echo "Stopping the Agent Proxy service. This will take a bit."
if ! systemctl stop aembit_agent_proxy.service; then
    echo "Unable to stop the Agent Proxy service."
    exit 1
fi

echo "Disabling the Agent Proxy service."
if ! systemctl disable aembit_agent_proxy.service; then
    echo "Unable to disable the Agent Proxy service."
    exit 1
fi

echo "Deleting the Agent Proxy systemd service file."
if ! rm /etc/systemd/system/aembit_agent_proxy.service; then
    echo "Unable to delete the service file."
    exit 1
fi 

echo "Reloading the systemd daemon."
if ! systemctl daemon-reload; then
    echo "Unable to reload systemd daemon."
    exit 1
fi

if ! systemctl reset-failed; then
    echo "Unable to reset failed systemd units."
    exit 1
fi

echo "Deleting the Aembit tenant's root certificate."
if ! rm /usr/local/share/ca-certificates/aembit.crt; then
    echo "Unable to delete the Aembit tenant's root certificate."
    exit 1
fi

echo "Refreshing the host's trusted CA certificates."
if ! update-ca-certificates -f; then
    echo "Unable to refresh the host's trusted CA certificates."
    exit 1
fi

echo "Removing the Agent Proxy journald configuration."
if ! rm /etc/systemd/journald@aembit_agent_proxy.conf; then
    echo "Unable to remove the Agent Proxy journald configuration."
    exit 1
fi

echo "Restarting journald."
if ! systemctl restart systemd-journald; then
    echo "Unable to restart journald."
    exit 1
fi

echo "Removing user."
if ! userdel -r "${AEMBIT_USER_NAME}"; then
    echo "Unable to remove the ${AEMBIT_USER_NAME} user.";
    exit 1
fi

echo "Removing the Agent Proxy version directory."
if ! rm -rf /opt/aembit/edge/agent_proxy/1.9.1256; then
    echo "Unable to remove the Agent Proxy version directory."
    exit 1
fi
