#!/bin/sh

set -e

if [ "${ARCH}" = "" ]; then
    ARCH=aarch64
fi

if [ "${PROFILE}" = "" ]; then
    PROFILE=debug
fi

USER_TARGET=${ARCH}-unknown-yggdrasil
USER_CARGO_OPTS="--target=${USER_TARGET}"

if [ "${PROFILE}" = "release" ]; then
    USER_CARGO_OPTS="${USER_CARGO_OPTS} --release"
fi

pstatus() {
    echo -e "[BUILD] \033[32;1m$@\033[0m"
}

die() {
    echo -e "[ERROR] \033[31;1m$@\033[0m" >&2
    exit 1
}

check_toolchain() {
    pstatus "Checking toolchain"
    if ! cargo +ygg-stage1 --version; then
        die "Yggdrasil OS Rust toolchain is not built/installed, see https://git.alnyan.me/yggdrasil/yggdrasil-rust"
    fi
}

pack_initrd() {
    local workspace_dir=$(pwd)
    local build_dir=target/${USER_TARGET}/${PROFILE}
    local root_dir=${build_dir}/rootfs

    mkdir -p "${root_dir}"
    mkdir -p "${root_dir}/sbin"
    mkdir -p "${root_dir}/bin"

    # init
    cp ${build_dir}/init ${root_dir}
    cp ${build_dir}/rc ${root_dir}/sbin/

    # shell
    cp ${build_dir}/shell ${root_dir}/bin/sh

    # sysutils
    cp ${build_dir}/mount ${root_dir}/sbin/
    cp ${build_dir}/login ${root_dir}/sbin/
    cp ${build_dir}/ls ${root_dir}/bin/
    cp ${build_dir}/hexd ${root_dir}/bin/
    cp ${build_dir}/colors ${root_dir}/bin/

    # red
    cp ${build_dir}/red ${root_dir}/bin/red

    cp -r ${workspace_dir}/etc ${root_dir}/

    cd "${root_dir}"
    mkdir -p dev
    touch dev/.do_not_remove

    tar cf ../initrd.tar `find . -type f -printf "%P\n"`
    cd -
}

check_toolchain

case "$1" in
    build|"")
        if [ "${CLEAN_BUILD}" = 1 ]; then
            cargo clean
        fi

        pstatus "Building userspace programs"
        cargo +ygg-stage1 build ${USER_CARGO_OPTS}

        pstatus "Creating initrd.tar"
        pack_initrd
        ;;
    **)
        ;;
esac