#!/sbin/openrc-run

description="Create s6 services for gettys on user-chosen terminals"

depend() {
  after dev-mount
}

makeservice() {
  set -e
  tty="$1"
  eval 'options="$GETTYS_'"$tty"'_OPTIONS"'
  eval 'baud="$GETTYS_'"$tty"'_BAUDRATE"'
  mkdir -p -m 0755 "/var/lib/s6/services/getty-$tty"
  {
    echo '#!/bin/execlineb -P'
    echo
    echo "/sbin/agetty $options -- $tty $baud"
  } > "/var/lib/s6/services/getty-$tty/run"
  chmod 0755 "/var/lib/s6/services/getty-$tty/run"
}

nomatchname() {
  for j in $GETTYS ; do
    if test "$j" = "$1" ; then
      return 1
    fi
  done
  return 0
}

notearly() {
  if test -d /etc/s6-linux-init/current/run-image/service/s6-linux-init-early-getty ; then
    if early=`head -n 1 /run/kernel_env/earlygetty` ; then
      early="${early%%,*}"
    else
      early=tty2
    fi
    test "$1" != "$early"
  fi
}

start() {
  set -e
  ebegin "Applying getty configuration"
  . /etc/conf.d/gettys

  todel=""
  for i in `ls -1 /var/lib/s6/services | grep ^getty-` ; do
    if nomatchname "${i##getty-}" ; then
      rm -f "/run/service/$i"
      todel="$todel $i"
    fi
  done

  for i in $GETTYS ; do
    if test -c /dev/"$i" && notearly "$i" ; then
      makeservice "$i"
      ln -nsf "/var/lib/s6/services/getty-$i" "/run/service/getty-$i"
    fi
  done

  s6-svscanctl -an /run/service
  if test -n "$todel" ; then
    ( sleep 1 && rm -rf $todel ) &
  fi
  eend $?
}