#!/bin/bash
# dde-desktop-vnc - turnkey headless remote access for the Deepin Desktop
# Environment on Amazon Linux 2023, using approach #1: treeland nested in an
# Xvnc X server (wlroots X11 backend, software renderer), reached over a VNC
# client tunneled through SSH.
#
# SECURITY: this starts Xvnc bound so it is reachable, but you MUST reach it
# over an SSH tunnel (ssh -L 5901:localhost:5901 ...). Do NOT open the VNC
# port (590X) in your security group.
#
# Usage:
#   dde-desktop-vnc start [DISPLAY] [GEOMETRY]   # e.g. dde-desktop-vnc start :1 1920x1080
#   dde-desktop-vnc stop  [DISPLAY]
#   dde-desktop-vnc status
set -e

DISP="${2:-:1}"
GEOM="${3:-1920x1080}"
VNCDIR="$HOME/.vnc"

ensure_setup() {
    mkdir -p "$VNCDIR"
    # One-time VNC password (override by setting DDE_VNC_PASSWORD before first run)
    if [ ! -f "$VNCDIR/passwd" ]; then
        local pw="${DDE_VNC_PASSWORD:-changeme}"
        printf '%s\n' "$pw" | vncpasswd -f > "$VNCDIR/passwd"
        chmod 600 "$VNCDIR/passwd"
        echo "[dde-desktop-vnc] wrote $VNCDIR/passwd (password: '$pw' - change with 'vncpasswd')"
    fi
    # xstartup launches the canonical DDE session in headless mode
    cat > "$VNCDIR/xstartup" <<'XS'
#!/bin/bash
exec > "$HOME/.vnc/dde.log" 2>&1
export DDE_HEADLESS=1
exec /usr/bin/dde-desktop-session
XS
    chmod +x "$VNCDIR/xstartup"
}

case "${1:-start}" in
    start)
        ensure_setup
        # XDG runtime dir for the Wayland socket
        export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
        mkdir -p "$XDG_RUNTIME_DIR"; chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null || true
        rm -f "/tmp/.X${DISP#:}-lock" "/tmp/.X11-unix/X${DISP#:}" 2>/dev/null || true
        vncserver "$DISP" -geometry "$GEOM" -depth 24 -localhost no
        echo "[dde-desktop-vnc] DDE session on $DISP ($GEOM)."
        echo "[dde-desktop-vnc] Tunnel it:  ssh -L 590${DISP#:}:localhost:590${DISP#:} <user>@<host>"
        echo "[dde-desktop-vnc] then point your VNC client at localhost:590${DISP#:}"
        ;;
    stop)
        vncserver -kill "$DISP" 2>/dev/null || true
        echo "[dde-desktop-vnc] stopped $DISP"
        ;;
    status)
        vncserver -list 2>/dev/null || true
        ;;
    *)
        echo "Usage: dde-desktop-vnc {start|stop|status} [DISPLAY] [GEOMETRY]" >&2
        exit 1
        ;;
esac
