#!/bin/sh

# Copyright 2026 Telemity Ltd

set -eu

SOURCE_PATH=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)

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

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

USER="dnsstream"
GROUP="dnsstream"

if [ "$(id -u)" -ne 0 ]; then
    echo "This installer must be run as root." >&2
    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
    fi
fi

install -d -m 0755 -o "$USER" -g "$GROUP" "$INSTALL_DIR"
install -d -m 0755 -o "$USER" -g "$GROUP" "$INSTALL_PATH"
install -d -m 0755 -o "$USER" -g "$GROUP" "$INSTALL_PATH/bin"
install -d -m 0755 -o "$USER" -g "$GROUP" "$INSTALL_PATH/data"
install -d -m 0755 -o "$USER" -g "$GROUP" "$SOCKET_DIR"
install -d -m 0755 -o "$USER" -g "$GROUP" "$SOCKET_PATH"

install -m 0755 -o "$USER" -g "$GROUP" "$SOURCE_PATH/bin/dnsstream.bin" "$INSTALL_PATH/bin/dnsstream.bin"
install -m 0755 -o "$USER" -g "$GROUP" "$SOURCE_PATH/uninstall.sh" "$INSTALL_PATH/bin/uninstall.sh"
install -m 0755 -o "$USER" -g "$GROUP" "$SOURCE_PATH/data/dnsstream.conf.default" "$INSTALL_PATH/data/dnsstream.conf.default"

if [ ! -f "${INSTALL_PATH}/data/dnsstream.conf" ]; then
    install -m 0640 -o "$USER" -g "$GROUP" "$SOURCE_PATH/data/dnsstream.conf.default" "$INSTALL_PATH/data/dnsstream.conf"
fi

cat > "/etc/systemd/system/telemity-dnsstream.service" <<EOF
[Unit]
Description=Telemity DnsStream
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=$USER
Group=$GROUP
ExecStart=$INSTALL_PATH/bin/dnsstream.bin run $INSTALL_PATH/data/dnsstream.conf
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload
systemctl enable "telemity-dnsstream.service"
