#!/usr/bin/env bash
# One-time configuration of GNOME Remote Desktop (system / headless remote
# login). Runs on first boot because grdctl talks to the running daemon.
#
# Optional /etc/gnome-remote-desktop/rdp.env:
#   GRD_SYSTEM_USER=rdp
#   GRD_SYSTEM_PASSWORD=...
# If unset, remote login is enabled but no greeter credential is configured
# (set one with: printf '%s\n%s\n' USER PASS | grdctl --system rdp set-credentials).
set -euo pipefail

GRD_USER=gnome-remote-desktop
STATE="/var/lib/${GRD_USER}"
TLS_DIR="${STATE}/.local/share/gnome-remote-desktop"
MARKER="${STATE}/.configured"

[[ -f "${MARKER}" ]] && exit 0

install -d -o "${GRD_USER}" -g "${GRD_USER}" "${TLS_DIR}"

if [[ ! -f "${TLS_DIR}/tls.key" ]]; then
  sudo -u "${GRD_USER}" openssl req -new -newkey rsa:4096 -days 720 -nodes -x509 \
    -subj "/CN=${GRD_CERT_CN:-fedora-remote}" \
    -out "${TLS_DIR}/tls.crt" -keyout "${TLS_DIR}/tls.key"
fi

grdctl --system rdp set-tls-key "${TLS_DIR}/tls.key"
grdctl --system rdp set-tls-cert "${TLS_DIR}/tls.crt"

# Pass username/password as arguments: grdctl's interactive prompt reads from a
# controlling terminal, which a system service does not have, so piping them in
# silently sets nothing (GRD then logs "Credentials are not set, denying client").
if [[ -n "${GRD_SYSTEM_PASSWORD:-}" ]]; then
  grdctl --system rdp set-credentials \
    "${GRD_SYSTEM_USER:-rdp}" "${GRD_SYSTEM_PASSWORD}"
fi

grdctl --system rdp enable
systemctl restart gnome-remote-desktop.service || true

# Open the RDP port in firewalld (best effort; firewalld may not be installed).
if command -v firewall-cmd >/dev/null 2>&1; then
  firewall-cmd --permanent --add-service=rdp >/dev/null 2>&1 || true
  firewall-cmd --reload >/dev/null 2>&1 || true
fi

touch "${MARKER}"
