#!/bin/sh

set -eu

do_cowsay() {
  cowsay_message=$(puavo-conf puavo.xsessions.cowsay.message)

  echo
  echo
  echo "$cowsay_message" | /usr/games/cowsay
  echo
  echo 'You can reboot this host by pressing ENTER.'
  echo
  read answer
  reboot
  sleep 600
}

# If we are starting this to tty, we must be in some special
# installation/update/recovery mode, and thus normal remote connection
# restrictions should not apply.
/usr/lib/puavo-ltsp-client/admin-remote-connections --accept-incoming \
  2>/dev/null || true

tty_dev=$(tty)
tty_n=$(echo "${tty_dev}" | sed -r -n 's|/dev/tty||p')

if [ -n "${tty_n}" ]; then
  if ! chvt "${tty_n}"; then
    echo "Could not chvt to ${tty_n}" >&2
    exit 1
  fi
fi

export LANG=en_US.UTF-8
setupcon

# suppress most kernel messages from this terminal
dmesg -n2

dm="$(puavo-conf puavo.xsessions.display_manager)"
case "$dm" in
  puavo-darkdm)
    ;;
  puavo-darkdm-cowsay)
    do_cowsay
    exit 0
    ;;
  puavo-darkdm-reset)
    exec tmux new-session /usr/lib/puavo-ltsp-install/puavo-reset
    ;;
  *)
    echo "Unsupported darkdm mode: '${dm}'" >&2
    exit 1
    ;;
esac

exec tmux new-session /usr/lib/puavo-ltsp-client/darkdm
