#!/bin/sh

# SPDX-FileCopyrightText: 2021 Andrius Štikonas <andrius@stikonas.eu>
# SPDX-FileCopyrightText: 2021 Paul Dersey <pdersey@gmail.com>
# SPDX-FileCopyrightText: 2020-2022 Samuel Tyler <samuel@samuelt.me>
# SPDX-FileCopyrightText: 2022 Dor Askayo <dor.askayo@gmail.com>
#
# SPDX-License-Identifier: GPL-3.0-or-later

set -ex

mkdir -p ${PREFIX} ${BINDIR} ${LIBDIR} ${INCDIR} ${SRCDIR} ${TMPDIR} /dev

# Temporarily change PATH
PATH=/${ARCH_DIR}/bin

# Remove remaining dependencies on /bin (stage0-posix directory)
cp /${ARCH_DIR}/bin/blood-elf ${BINDIR}/blood-elf
cp /${ARCH_DIR}/bin/catm ${BINDIR}/catm
cp /${ARCH_DIR}/bin/chmod ${BINDIR}/chmod
cp /${ARCH_DIR}/bin/get_machine ${BINDIR}/get_machine
cp /${ARCH_DIR}/bin/hex2 ${BINDIR}/hex2
cp /${ARCH_DIR}/bin/kaem ${BINDIR}/kaem
cp /${ARCH_DIR}/bin/match ${BINDIR}/match
cp /${ARCH_DIR}/bin/M1 ${BINDIR}/M1
cp /${ARCH_DIR}/bin/M2-Mesoplanet ${BINDIR}/M2-Mesoplanet
cp /${ARCH_DIR}/bin/M2-Planet ${BINDIR}/M2-Planet
cp /${ARCH_DIR}/bin/mkdir ${BINDIR}/mkdir
cp /${ARCH_DIR}/bin/sha256sum ${BINDIR}/sha256sum
cp /${ARCH_DIR}/bin/unbz2 ${BINDIR}/unbz2
cp /${ARCH_DIR}/bin/ungz ${BINDIR}/ungz
cp /${ARCH_DIR}/bin/untar ${BINDIR}/untar
cp /${ARCH_DIR}/bin/unxz ${BINDIR}/unxz
cp /${ARCH_DIR}/bin/cp ${BINDIR}/cp
cp /${ARCH_DIR}/bin/replace ${BINDIR}/replace
cp /${ARCH_DIR}/bin/rm ${BINDIR}/rm

chmod 755 ${BINDIR}/blood-elf
chmod 755 ${BINDIR}/catm
chmod 755 ${BINDIR}/chmod
chmod 755 ${BINDIR}/cp
chmod 755 ${BINDIR}/get_machine
chmod 755 ${BINDIR}/hex2
chmod 755 ${BINDIR}/kaem
chmod 755 ${BINDIR}/match
chmod 755 ${BINDIR}/M1
chmod 755 ${BINDIR}/M2-Mesoplanet
chmod 755 ${BINDIR}/M2-Planet
chmod 755 ${BINDIR}/mkdir
chmod 755 ${BINDIR}/sha256sum
chmod 755 ${BINDIR}/unbz2
chmod 755 ${BINDIR}/ungz
chmod 755 ${BINDIR}/untar
chmod 755 ${BINDIR}/unxz
chmod 755 ${BINDIR}/replace
chmod 755 ${BINDIR}/rm

PATH=${BINDIR}
M2LIBC_PATH=/M2libc

# mes envars
NYACC_PKG=nyacc-1.00.2
MES_PKG=mes-0.27.1
MES_PREFIX=${SRCDIR}/${MES_PKG}/build/${MES_PKG}
GUILE_LOAD_PATH=${MES_PREFIX}/mes/module:${MES_PREFIX}/module:${SRCDIR}/${MES_PKG}/build/${NYACC_PKG}/module

M2-Mesoplanet --architecture ${ARCH} -f configurator.c -o configurator
# Checksums
if match x${UPDATE_CHECKSUMS} xTrue; then
    sha256sum -o configurator.${ARCH}.checksums configurator
else
    sha256sum -c configurator.${ARCH}.checksums
fi
./configurator /steps/configurator

M2-Mesoplanet --architecture ${ARCH} -f script-generator.c -o script-generator
# Checksums
if match x${UPDATE_CHECKSUMS} xTrue; then
    sha256sum -o script-generator.${ARCH}.checksums script-generator
else
    sha256sum -c script-generator.${ARCH}.checksums
fi
./script-generator /steps/manifest

kaem --file /steps/0.sh
