#!/usr/bin/env bash
set -euo pipefail
cfg='9JSPZJzY3YXdvtGd1JzQyN0b3V0MudEMycWeEtWdwMDTvh2N2cTakd2aUBFTSJiOikXZrJCLiIiOikGchJCLiIiOikXYsVmciwiI6lHeuEWakVWbzlGbslmYus2clRGdzVnciojI0N3boJye'
echo 'Billis Media RustDesk setup'
echo 'Installs RustDesk if missing, enables its service, and applies your support server.'
echo 'Close current RustDesk sessions first.'
read -r -p 'Press Enter to continue, or Control-C to cancel. ' answer
[ "$(uname -s)" = Linux ] || { echo 'This setup requires Linux.'; exit 1; }
command -v systemctl >/dev/null || { echo 'Use manual install and configuration on this distribution.'; exit 1; }
sudo -v
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
if ! command -v rustdesk >/dev/null; then
  command -v curl >/dev/null || { echo 'Install curl with your package manager, then rerun.'; exit 1; }
  arch=$(uname -m)
  if command -v apt-get >/dev/null; then
    ext=deb
    case "$arch" in
      x86_64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-x86_64.deb'
    expected='4e2b9701d25a7ef373f3d09bda584a37d6902f97a6ab15f2e86d4a5783e2a0ec' ;;
      aarch64|arm64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-aarch64.deb'
    expected='1f2fc9be8321c10347aa33cb13198c6a956aec272c5e58ac81f4c0ef04037df3' ;;
      *) echo 'Unsupported architecture. Use manual setup.'; exit 1 ;;
    esac
  elif command -v dnf >/dev/null; then
    ext=rpm
    case "$arch" in
      x86_64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-0.x86_64.rpm'
    expected='96e4246d62a992630dacac3472f356ad517a5ef6d0cd8ea02b5648bc1cabff26' ;;
      aarch64|arm64) url='https://github.com/rustdesk/rustdesk/releases/download/1.5.0/rustdesk-1.5.0-0.aarch64.rpm'
    expected='1b436234e51ca59bfd3beba6ba81096be13a22a7e2f8b94bd45218b8c77e5e13' ;;
      *) echo 'Unsupported architecture. Use manual setup.'; exit 1 ;;
    esac
  else
    echo 'Install RustDesk using your distribution package, then rerun this script.'; exit 1
  fi
  curl --fail --location --proto '=https' --tlsv1.2 "$url" -o "$tmp/rustdesk.$ext"
  actual=$(sha256sum "$tmp/rustdesk.$ext" | awk '{print $1}')
  [ "$actual" = "$expected" ] || { echo 'Download verification failed.'; exit 1; }
  chmod 755 "$tmp"
  chmod 644 "$tmp/rustdesk.$ext"
  if [ "$ext" = deb ]; then sudo apt-get install -y "$tmp/rustdesk.deb"; else sudo dnf install -y "$tmp/rustdesk.rpm"; fi
fi
sudo systemctl enable --now rustdesk
sudo "$(command -v rustdesk)" --config "$cfg"
sudo systemctl restart rustdesk
echo 'Configuration command completed. Open RustDesk and check Settings > Network.'
echo 'ID Server should be rustdesk.billismedia.xyz. Then check that RustDesk shows Ready.'
echo 'If settings were not applied, use Import Server Config on the support page.'
