#!/usr/bin/env sh

COMPILER_LIST_SPECS=$(jq -Mr '.stack | .core_compiler as $core | .compilers | map("\(.spec)@\(.spec_version) %\($core)")[]' config.json)

echo "Getting system compiler"
spack/bin/spack compiler find --scope system /usr

spack/bin/spack spec \
    --install-status \
    --namespaces \
    --long \
    --types \
    ${COMPILER_LIST_SPECS}

spack/bin/spack spec \
    --install-status \
    --namespaces \
    --long \
    --types \
    --json \
    ${COMPILER_LIST_SPECS} > compilers_spec.json

echo "Compilers to install:"
echo "${COMPILER_LIST_SPECS}"

spack/bin/spack install \
    --log-file spack-install.xml \
    --log-format junit \
    --fail-fast \
    --show-log-on-error \
    ${COMPILER_LIST_SPECS}

hashes=$(jq -Mr '.spec.nodes | map("/\(.hash)") | join(" ")' compilers_spec.json)

echo "Adding packages to buildcache"
spack/bin/spack buildcache create \
    --update-index \
    --key EDC904DCE3D2E84E \
    /buildcache ${hashes}

core_compiler=$(jq -Mrc '.stack | .core_compiler' config.json)
compilers=$(jq -Mrc '.stack | .compilers | to_entries | map("\(.key)@\(.value.version)")' config.json)
compilers_specs=$(jq -Mrc '.stack | .compilers | map("\(.spec)@\(.spec_version)")' config.json)

cat > compiler_definitions.yaml << EOF
definitions:
  - core_compiler: [ ${core_compiler} ]
  - compilers: ${compilers}
  - compilers_specs: ${compilers_specs}
EOF

cat compiler_definitions.yaml

for compiler_hash in $(echo ${hashes}); do
    location=$(spack/bin/spack location -i ${compiler_hash})
    echo "Checking for compiler in locations:"
    echo "  - ${location}"
    echo "  - ${location}/compiler/latest/linux"

    spack/bin/spack compiler find \
        --scope system \
        ${location} \
        ${location}/compiler/latest/linux
done
