#!/bin/bash

# omarchy:summary=Remove Sunshine and close Omarchy-managed Moonlight streaming ports.
# omarchy:requires-sudo=true

set -e

TCP_PORTS=(47984 47989 48010)
UDP_PORTS=(5353 47998 47999 48000 48002 48010)
# 100.64.0.0/10 covers the Tailscale CGNAT range, mirroring the install side.
PRIVATE_CIDRS=(10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 100.64.0.0/10)
SUNSHINE_ADMIN_APP="Sunshine Admin"
HYPR_AUTOSTART_FILE="$HOME/.config/hypr/autostart.lua"
HYPR_AUTOSTART_ENTRY='o.launch_on_start("sunshine")'

delete_firewalld_rule() {
  sudo firewall-cmd --permanent --remove-rich-rule="$@" >/dev/null 2>&1 || true
}

close_firewalld_port_for_private_lans() {
  local proto="$1"
  local port="$2"
  local cidr

  for cidr in "${PRIVATE_CIDRS[@]}"; do
    delete_firewalld_rule "rule family=ipv4 source address=$cidr port port=$port protocol=$proto accept"
  done
}

close_firewalld_ports() {
  local port

  if omarchy-cmd-missing firewall-cmd; then
    return
  fi

  for port in "${TCP_PORTS[@]}"; do
    close_firewalld_port_for_private_lans tcp "$port"
  done

  for port in "${UDP_PORTS[@]}"; do
    close_firewalld_port_for_private_lans udp "$port"
  done

  sudo firewall-cmd --reload
}

disable_hyprland_autostart() {
  if [[ -f $HYPR_AUTOSTART_FILE ]]; then
    sed -i "\|^$HYPR_AUTOSTART_ENTRY$|d" "$HYPR_AUTOSTART_FILE"
  fi
}

systemctl --user disable --now sunshine 2>/dev/null || true
omarchy-pkg-drop sunshine
flatpak uninstall -y --user dev.lizardbyte.app.Sunshine 2>/dev/null || true
omarchy-webapp-remove "$SUNSHINE_ADMIN_APP" 2>/dev/null || true
disable_hyprland_autostart
close_firewalld_ports

echo ""
echo "Sunshine has been removed and its Omarchy-managed Moonlight streaming ports have been closed."
