#!/bin/sh
# Prepares wayvnc's auth material. Deliberately does NOT set a password.
set -eu

. /etc/steamtv-agent/config.env

mkdir -p /etc/wayvnc
chmod 0755 /usr/local/bin/start-wayvnc

# wayvnc's RSA-AES auth needs a key pair; it is machine-local and carries no secret
# that belongs in git, so generating it at build time is fine.
if [ ! -f /etc/wayvnc/rsa_key.pem ]; then
  openssl genrsa -out /etc/wayvnc/rsa_key.pem 2048 2>/dev/null
fi

# Self-signed TLS material, needed only by wayvnc <= 0.6 whose auth path is TLS-based
# rather than RSA-AES. Harmless on newer versions.
if [ ! -f /etc/wayvnc/tls_key.pem ]; then
  openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
    -keyout /etc/wayvnc/tls_key.pem -out /etc/wayvnc/tls_cert.pem \
    -subj "/CN=steam-tv-box" 2>/dev/null
fi

# Sentinel, not a password. start-wayvnc refuses to launch while this value is still
# here, so the failure mode of "operator forgot to set a password" is "no VNC server"
# rather than "an unauthenticated VNC server on the LAN". A real value must never be
# committed — see hosts/steam-tv-box/README.md.
if [ ! -f /etc/wayvnc/wayvnc-password ]; then
  printf 'CHANGEME-SET-ON-FIRST-BOOT\n' > /etc/wayvnc/wayvnc-password
fi

chmod 0600 /etc/wayvnc/wayvnc-password /etc/wayvnc/rsa_key.pem /etc/wayvnc/tls_key.pem
chown "${KIOSK_USERNAME}:${KIOSK_USERNAME}" \
  /etc/wayvnc/wayvnc-password /etc/wayvnc/rsa_key.pem /etc/wayvnc/tls_key.pem
chmod 0644 /etc/wayvnc/tls_cert.pem /etc/wayvnc/config
