#!/bin/execlineb -P
#
# anopa - Copyright (C) 2015 Olivier Brunel
#
# aa-stage0
# 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/
#
#
/bin/emptyenv /bin/s6-envdir /etc/anopa/env /bin/exec

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

# aa-* tools will send output to both 1 & 2 via -D
fdclose 3
fdmove 2 4
foreground { aa-echo -D "Stage 0: Mounting root file system..." }

# Safety
cd /
umask 022

# Start services
foreground { if -n
{
  if { emptyenv -c s6-setsid aa-ctty -Ds aa-start -D -r /services -l onboot }
  foreground {
    # if "break" was specified on kernel cmdline, let's open a shell
    if -t { aa-incmdline -Dqf /root-fs/proc/cmdline break }
    foreground { aa-echo -DB "Break requested" }
    foreground { aa-echo -Dt "Trying to open a shell; " +g exit +w " to continue" }
    emptyenv -c sh -i
  }
}

# aa-start failed (i.e. an essential service failed to be started), so we assume
# the root fs wasn't mounted: try a shell so user has a chance to fix things
foreground { aa-echo -DBe "Mouting root file system failed" }
foreground { aa-echo -Dt "Trying to open a shell; " +g exit +w " to continue" }
fdmove -c 2 1
emptyenv -c sh -i
}

if { aa-echo -DB "Moving /root-fs to /..." }
# First we mount bind the rootfs (initramfs) onto /run/initramfs so we can come
# back to it for stage 4
if { aa-mount -DBd / /root-fs/run/initramfs }
fdmove -c 2 1
backtick -n -D /sbin/init INIT { aa-incmdline -rf /root-fs/proc/cmdline init }
import -u INIT
cd /root-fs
if { aa-mount -M . / }
./run/initramfs/bin/emptyenv -c ./run/initramfs/bin/aa-chroot . ${INIT}
