#!/bin/sh

# Copyright 2026 Telemity Ltd

set -eu

INSTALL_DIR="/opt/telemity"
SOCKET_DIR="/run/telemity"

INSTALL_PATH="$INSTALL_DIR/dnsstream"
SOCKET_PATH="$SOCKET_DIR/dnsstream"

if [ "$(id -u)" -ne 0 ]; then
    echo "This uninstaller must be run as root." >&2
    exit 1
fi

if [ "$#" -ne 1 ] || [ "$1" != "--confirm" ]; then
    echo "This script will uninstall Telemity DnsStream from this machine."
    echo "If you are sure you want to continue, please run the script again with the --confirm flag."
    exit 1
fi

if command -v systemctl >/dev/null 2>&1; then
    if systemctl list-unit-files "telemity-dnsstream.service" >/dev/null 2>&1; then
        systemctl stop "telemity-dnsstream.service" >/dev/null 2>&1 || true
        systemctl disable "telemity-dnsstream.service" >/dev/null 2>&1 || true
    fi
fi

if [ -f "/etc/systemd/system/telemity-dnsstream.service" ]; then
    rm -f "/etc/systemd/system/telemity-dnsstream.service"
fi

if command -v systemctl >/dev/null 2>&1; then
    systemctl daemon-reload
    systemctl reset-failed "telemity-dnsstream.service" >/dev/null 2>&1 || true
fi

rm -rf "$INSTALL_PATH"
rm -rf "$SOCKET_PATH"

rmdir "$INSTALL_DIR" >/dev/null 2>&1 || true
rmdir "$SOCKET_DIR" >/dev/null 2>&1 || true
