#!/bin/bash
# THN Remote Support - Linux Installer
# Pre-configured for help.kriskirkland.com

set -e
SERVER="help.kriskirkland.com"
KEY="I15NQEE2HU2fPQQLpVfluq8ShuNq0L4F6MGUo5Vg7Dg="

if [ -f /etc/os-release ]; then
    . /etc/os-release
    UPSTREAM_ID="${ID_LIKE,,}"
fi

echo "Fetching latest RustDesk version..."
LVER=$(curl -s https://api.github.com/repos/rustdesk/rustdesk/releases/latest | grep '"tag_name"' | cut -d'"' -f4)
echo "Installing RustDesk $LVER..."

if [ "${ID}" = "debian" ] || [ "${ID}" = "ubuntu" ] || echo "${UPSTREAM_ID}" | grep -q "debian\|ubuntu"; then
    curl -L "https://github.com/rustdesk/rustdesk/releases/download/${LVER}/rustdesk-${LVER}-x86_64.deb" -o /tmp/rustdesk.deb
    apt install -fy /tmp/rustdesk.deb
    rm /tmp/rustdesk.deb
elif [ "${ID}" = "centos" ] || [ "${ID}" = "rhel" ] || [ "${ID}" = "fedora" ] || echo "${UPSTREAM_ID}" | grep -q "rhel\|fedora"; then
    curl -L "https://github.com/rustdesk/rustdesk/releases/download/${LVER}/rustdesk-${LVER}-0.x86_64.rpm" -o /tmp/rustdesk.rpm
    yum localinstall -y /tmp/rustdesk.rpm
    rm /tmp/rustdesk.rpm
else
    echo "Unsupported Linux distribution: $ID"
    exit 1
fi

# Write config for current user and root
for CONFIG_DIR in "$HOME/.config/rustdesk" "/root/.config/rustdesk"; do
    mkdir -p "$CONFIG_DIR"
    cat > "$CONFIG_DIR/RustDesk2.toml" << TOML
rendezvous_server = 'help.kriskirkland.com'
nat_type = 1
serial = 3

[options]
key = 'I15NQEE2HU2fPQQLpVfluq8ShuNq0L4F6MGUo5Vg7Dg='
custom-rendezvous-server = 'help.kriskirkland.com'
api-server = 'https://help.kriskirkland.com'
relay-server = 'help.kriskirkland.com'
enable-audio = 'N'
TOML
done

systemctl restart rustdesk 2>/dev/null || true
echo ""
echo "Done! RustDesk is configured for $SERVER"
echo "Your ID: $(grep -w id "$HOME/.config/rustdesk/RustDesk.toml" 2>/dev/null | awk '{print $3}' || echo '(start RustDesk to generate)')"
