#!/bin/sh
# Launches wayvnc with a password that is never stored in the repo or in /etc/wayvnc/config.
# Installed to /usr/local/bin/start-wayvnc, started from the sway config.
set -eu

BASE_CONFIG=/etc/wayvnc/config
PASSWORD_FILE=/etc/wayvnc/wayvnc-password
SENTINEL='CHANGEME-SET-ON-FIRST-BOOT'

if [ ! -r "$PASSWORD_FILE" ]; then
  echo "start-wayvnc: $PASSWORD_FILE is missing or unreadable — refusing to start." >&2
  exit 1
fi

PASSWORD="$(head -n 1 "$PASSWORD_FILE" | tr -d '\r\n')"

# Fail closed. An operator who forgets this step gets no remote access, rather than a
# remote-control channel anyone on the LAN can open.
if [ -z "$PASSWORD" ] || [ "$PASSWORD" = "$SENTINEL" ]; then
  echo "start-wayvnc: no wayvnc password set. Run, as root, on this machine:" >&2
  echo "  openssl rand -base64 24 > $PASSWORD_FILE && chmod 600 $PASSWORD_FILE" >&2
  echo "  chown $(id -un):$(id -gn) $PASSWORD_FILE" >&2
  echo "Then restart the session. Refusing to start an unauthenticated VNC server." >&2
  exit 1
fi

RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/wayvnc"
mkdir -p "$RUNTIME_DIR"
chmod 700 "$RUNTIME_DIR"

RUNTIME_CONFIG="$RUNTIME_DIR/config"
umask 077
cp "$BASE_CONFIG" "$RUNTIME_CONFIG"
printf 'password=%s\n' "$PASSWORD" >> "$RUNTIME_CONFIG"

exec wayvnc --config="$RUNTIME_CONFIG"
