#!/bin/bash
set -euo pipefail
mkdir -p /workspace /run/sshd
# An immutable machine identity survives stop/start; forks get a new identity
# and new host keys. Credentials and current launch configuration live in /run.
if [ "$(cat /etc/beam-vm-identity 2>/dev/null || true)" != "$BEAM_VM_ID" ]; then
  rm -f /etc/ssh/ssh_host_*
  printf '%s\n' "$BEAM_VM_ID" > /etc/beam-vm-identity
fi
if [ "${BEAM_VM_SSH:-false}" = true ]; then
  if [ ! -f /etc/ssh/ssh_host_ed25519_key ]; then
    ssh-keygen -q -t ed25519 -N '' -f /etc/ssh/ssh_host_ed25519_key
  fi
  printf '%s\n' "${BEAM_VM_SSH_PUBLIC_KEY:-}" > /run/beam-vm/authorized_keys
  chmod 0600 /run/beam-vm/authorized_keys
fi
export HOME=/root LANG=C.UTF-8
if [ "${BEAM_VM_DESKTOP:-false}" = true ]; then
  export DISPLAY=:1 XAUTHORITY=/run/beam-desktop/.Xauthority
fi
# Managed services and user units start through the normal systemd boot graph.
cd /workspace
exec "$@"
