#!/usr/bin/env bash
set -euo pipefail

SERVER="rustdesk.allirama.com.py"
ID_PORT="21116"
RELAY_PORT="21117"
PUBKEY=""

# Directorio del script
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
DEB_FILE="${SCRIPT_DIR}/rustdesk-1.4.2-x86_64.deb"

if [[ $EUID -ne 0 ]]; then
  echo "[ERROR] Ejecutar como root: sudo $0"
  exit 1
fi

if [[ ! -f "$DEB_FILE" ]]; then
  echo "[ERROR] No se encuentra $DEB_FILE"
  exit 1
fi

echo "Instalando RustDesk..."
dpkg -i "$DEB_FILE" || apt-get -y -f install

CFG_USER="${SUDO_USER:-$USER}"
HOME_DIR="$(eval echo ~${CFG_USER})"
CFG_DIR_USER="$HOME_DIR/.config/rustdesk"
CFG_DIR_ROOT="/root/.config/rustdesk"

mkdir -p "$CFG_DIR_USER" "$CFG_DIR_ROOT"

write_toml() {
  local path="$1"
  {
    echo "rendezvous_server = \"${SERVER}:${ID_PORT}\""
    echo "relay_server = \"${SERVER}:${RELAY_PORT}\""
    [[ -n "$PUBKEY" ]] && echo "key = \"${PUBKEY}\""
  } > "$path"
  chmod 644 "$path"
}
write_toml "$CFG_DIR_USER/RustDesk2.toml"
write_toml "$CFG_DIR_ROOT/RustDesk2.toml"
chown -R "$CFG_USER":"$CFG_USER" "$CFG_DIR_USER"

mkdir -p "$HOME_DIR/.config/systemd/user"
cat > "$HOME_DIR/.config/systemd/user/rustdesk.service" <<'UNIT'
[Unit]
Description=RustDesk (usuario)
After=network-online.target
[Service]
ExecStart=/usr/bin/rustdesk
Restart=on-failure
[Install]
WantedBy=default.target
UNIT
chown -R "$CFG_USER":"$CFG_USER" "$HOME_DIR/.config/systemd/user"
runuser -l "$CFG_USER" -c 'systemctl --user daemon-reload && systemctl --user enable --now rustdesk.service' || true

if command -v ufw >/dev/null 2>&1; then
  ufw allow 21115/tcp || true
  ufw allow 21116/tcp || true
  ufw allow 21116/udp || true
fi

echo "✅ Listo. RustDesk configurado para ${SERVER}."

