#!/usr/bin/env nix-shell
#!nix-shell -i bash -p bash coreutils gnutar

# Generate a sources.nix for a version of GNU mes. Creates lists of source files
# from build-aux/configure-lib.sh.
#
# You may point this tool at a manually downloaded tarball, but more ideal is
# using the source tarball from Nixpkgs. For example:
#
# MES_TARBALL="$(nix-build --no-link -A minimal-bootstrap.mes.src ../../../../..)"
# ./gen-sources.sh "$MES_TARBALL" > ./new-sources.nix

set -eu

# Supported platforms
ARCHS="x86"
KERNELS="linux"
COMPILERS="mescc gcc"


format() {
  echo "["
  echo $* | xargs printf '      "%s"\n'
  echo "    ]"
}

gen_sources() {
  # Configuration variables used by configure-lib.sh
  export mes_libc=mes
  export mes_cpu=$1
  export mes_kernel=$2
  export compiler=$3

  # Populate source file lists
  source $CONFIGURE_LIB_SH

  cat <<EOF
  $mes_cpu.$mes_kernel.$compiler = {
    libc_mini_SOURCES = $(format $libc_mini_SOURCES);
    libmescc_SOURCES = $(format $libmescc_SOURCES);
    libtcc1_SOURCES = $(format $libtcc1_SOURCES);
    libc_SOURCES = $(format $libc_SOURCES);
    libc_tcc_SOURCES = $(format $libc_tcc_SOURCES);
    libc_gnu_SOURCES = $(format $libc_gnu_SOURCES);
    mes_SOURCES = $(format $mes_SOURCES);
  };
EOF
}


MES_TARBALL=$1
if [ ! -f $MES_TARBALL ]; then
    echo "Provide path to mes-x.x.x.tar.gz as first argument" >&2
    exit 1
fi
echo "Generating sources.nix from $MES_TARBALL" >&2

TMP=$(mktemp -d)
cd $TMP
echo "Workdir: $TMP" >&2

echo "Extracting $MES_TARBALL" >&2
tar --strip-components 1 -xf $MES_TARBALL

CONFIGURE_LIB_SH="$TMP/build-aux/configure-lib.sh"
if [ ! -f $CONFIGURE_LIB_SH ]; then
    echo "Could not find mes's configure-lib.sh script at $CONFIGURE_LIB_SH" >&2
    exit 1
fi

# Create dummy config expected by configure-lib.sh
touch config.sh
chmod +x config.sh


echo "Configuring with $CONFIGURE_LIB_SH" >&2

cat <<EOF
# This file is generated by ./gen-sources.sh.
# Do not edit!
{
EOF

for arch in $ARCHS; do
  for kernel in $KERNELS; do
    for compiler in $COMPILERS; do
      gen_sources $arch $kernel $compiler
    done
  done
done

cat <<EOF
}
EOF
