#!/bin/sh
# Tool to build tools to build the temporary system
set -e
umask 022

download_only=false
if [ "$1" = "download" ]; then
    download_only=true
fi

command -v astronaut >/dev/null 2>&1 || {
    echo 'Can'\''t find astronaut in $PATH' 1>&2
    exit 1
}

if [ "$download_only" = false ]; then
    if [ ! "$rocket" ]; then
        echo 'Please set the $rocket variable' 1>&2
        exit 1
    fi

    if [ "$(readlink /tools)" != "$(realpath "$rocket")/tools" ]; then
        echo "Please create a symlink from /tools to $(realpath "$rocket")/tools" 1>&2
        exit 1
    fi
fi

# Options for supported shells
if [ "$(basename "$(readlink /bin/sh)")" = "bash" ]; then
    shellopts="+h"
fi

# Know where them satellites are
satellite_dir="$(dirname "$(realpath "$0")")/satellites"

envrun() {
    if [ "$download_only" = true ]; then
        $@
        return
    fi

    env -i \
        HOME="$HOME" \
        TERM="$TERM" \
        LC_ALL=C \
        PATH="/tools/bin:$PATH" \
        MAKEFLAGS="$MAKEFLAGS" \
        rocket="$rocket" \
        target="$(uname -m)-rocket-linux-gnu" \
        /bin/sh "$shellopts" "$@"
}

astrobuild() {
    if [ "$download_only" = true ]; then
        envrun astronaut -d "$satellite_dir/$1.sat"
    else
        envrun astronaut -i "$rocket" "$satellite_dir/$1.sat"
    fi
}

# Needed for x86_64
if [ "$download_only" = false ]; then
    mkdir -p "$rocket/tools/lib"
    ln -sf lib "$rocket/tools/lib64"
fi

# Just enter the environment
#envrun

# List of packages to build

# Toolchain
astrobuild "binutils-1"
astrobuild "gcc-1"
astrobuild "linux-api"
astrobuild "glibc"
astrobuild "libstdcxx"
astrobuild "binutils-2"
astrobuild "gcc-2"

# Utilities
astrobuild "busybox"
astrobuild "bash"
astrobuild "gawk"
astrobuild "make"
astrobuild "m4"

# Testing
astrobuild "tcl-core"
astrobuild "expect"
astrobuild "dejagnu"
astrobuild "check"

# Package management
astrobuild "perl"
astrobuild "stow"
astrobuild "openssl"
astrobuild "ca-certificates"
astrobuild "curl"
astrobuild "astronaut"