#!@BINDIR@/execlineb -P
#
# anopa - Copyright (C) 2015 Olivier Brunel
#
# aa-stage2
# Copyright (C) 2015 Olivier Brunel <jjk@jjacky.com>
#
# This file is part of anopa.
#
# anopa is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# anopa is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# anopa. If not, see http://www.gnu.org/licenses/
#

# Set up a pipe to log messages
piperw 3 4
background
{
  fdclose 4 fdmove 0 3
  redirfd -a 1 /run/initramfs/boot.log
  fdmove -c 2 1
  s6-tai64n
}
fdclose 3
fdmove 2 4

if -n -t
{
  # We want the actual tty on stdin
  backtick -n TTY { aa-tty }
  import -u TTY
  redirfd -r 0 ${TTY}
  # Reopen the console for stdout
  redirfd -w 1 /dev/console
  # And start everything
  foreground { aa-echo -DB "Stage 2: Initializing system..." }
  backtick -n -D onboot LISTDIR { aa-incmdline -Drs aa }
  import -u LISTDIR
  # We have a tty in stdin, become session leader and set controlling terminal.
  # This is so Ctrl+C will trigger a SIGINT to aa-start, so one can manually
  # timeout a service.
  if { emptyenv -c s6-setsid aa-ctty -D aa-start -D -l /etc/anopa/listdirs/${LISTDIR} }
  foreground { aa-echo -DB "System ready." }
  # close logger
  fdmove -c 2 1
  # no more input
  redirfd -r 0 /dev/null
  # move log to file system
  if -n -t { aa-mvlog /run/initramfs/boot.log /var/log/boot }
  # show (& log) a warning
  pipeline { aa-echo -DBw "Failed to save /run/initramfs/boot.log to /var/log/boot" }
  redirfd -a 1 /run/initramfs/boot.log
  s6-tai64n
}

# Something went wrong, likely aa-start failed (i.e. an essential service failed
# to be started), so we assume there's not event a getty: try a shell so user
# has a chance to fix things
redirfd -r 0 /dev/console
redirfd -w 1 /dev/console
foreground { aa-echo -DBe "System initialization failed" }
fdmove -c 2 1
foreground { aa-echo -t "Trying to open a shell..." }
emptyenv -c sh -i
